给定以下具有 2 个隐式的对象:
scala> object Foo {
| implicit def stringToInt(x: String) = 555
| implicit def stringToBoolean(x: String) = true
| }
warning: there were two feature warnings; re-run with -feature for details
defined object Foo
我可以使用它们:
scala> def f(x: Int) = x
f: (x: Int)Int
scala> import Foo._
import Foo._
scala> f("asdf")
res0: Int = 555
scala> def g(b: Boolean) = b
g: (b: Boolean)Boolean
scala> g("asdfasdf")
res1: Boolean = true
然后,我尝试禁用stringToInt
隐含的。
scala> import Foo.{stringToInt => _}
import Foo.{stringToInt=>_}
但显然,这不起作用。
scala> f("adsfasdf")
res2: Int = 555
通配符导入隐式后,是否可以隐藏它们?
基本上,我想使用所有Foo
的隐式,减去一个,stringToInt
.
注意-当然我可以简单地做import Foo.stringToBoolean
只是,但是,对于我的场景,Foo
有大约 25 个导入,我想使用其中的 24 个。因此,使用全部,然后减一更简洁。
REPL 只是近似从历史记录中导入什么,一种近似总是使用导入的隐式。
在普通代码中,您可以通过隐藏标识符来禁用隐式。
最好的镜头是:
scala> object X { val stringToInt = 0 }
defined object X
scala> import X._
import X._
scala> f("asdf")
<console>:20: error: type mismatch;
found : String("asdf")
required: Int
f("asdf")
^
or
scala> implicit val stringToInt = 0
stringToInt: Int = 0
这个想法是将遮蔽变量引入到当前行的 REPL 模板的范围中。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)