问题描述
给出以下带有2个隐式对象:
Given the following object with 2 implicits:
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
隐式.
Then, I tried to disable the stringToInt
implicit.
scala> import Foo.{stringToInt => _}
import Foo.{stringToInt=>_}
但是,显然那是行不通的.
But, evidently, that did not work.
scala> f("adsfasdf")
res2: Int = 555
通配符导入隐式后,是否可以隐藏它们?
After wildcard importing implicits, is it possible to hide them?
基本上,我想使用Foo
的所有隐式变量,减去一个单独的stringToInt
.
Basically, I'd like to use all of Foo
's implicits, minus a single one, stringToInt
.
注意-当然,我只能简单地执行import Foo.stringToBoolean
,但是,对于我的情况,Foo
具有〜25个导入,我想使用其中的24个.因此,使用全部,然后减去一个会更简洁.
Note - of course I could simply do import Foo.stringToBoolean
only, but, for my scenario, Foo
has ~25 imports, and I want to use 24 of them. As a result, it's more concise to use all, and then subtract one.
推荐答案
REPL只是近似地从历史中导入什么,一种近似总是使用导入的隐式.
The REPL just approximates what to import from history, and one approximation is always to use imported implicits.
在常规代码中,您可以通过隐藏标识符来禁用隐式.
In normal code, you would disable an implicit by shadowing the identifier.
最好的镜头是:
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")
^
或
scala> implicit val stringToInt = 0
stringToInt: Int = 0
想法是将阴影变量引入当前行的REPL模板的范围.
The idea is to introduce the shadowing variable into the scope of the REPL template for the current line.
这篇关于通配符导入,然后隐藏特殊隐式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!