在编译时指定合法隐含和/或非法隐含? [英] Specifying Legal and/or Illegal Implicits at Compile-time?
问题描述
比方说,我有两个特定的object
可以从中检索导入.假设两个对象都有多个我想使用的有用的导入.为了简化本示例,我仅包括1:
Let's say that I have two particular object
's from which I retrieve imports. Assume that both objects have multiple, useful imports that I want to use. I'm only including 1 for simplicity of this example:
scala> object Implicits1 { implicit def good: String => Int = _ => 42 }
defined object Implicits1
scala> object Implicits2 { implicit def bad: String => Int = _ => 666 }
defined object Implicits2
然后,给定foo
:
scala> def foo(x: Int): Int = x
foo: (x: Int)Int
我执行通配符导入以获取隐式:
I perform my wildcard imports to get implicits:
scala> import Implicits1._
import Implicits1._
scala> import Implicits2._
import Implicits2._
在REPL上运行foo(".")
表示Implicits2.bad
的隐式已解决:
Running foo(".")
on the REPL shows that Implicits2.bad
's implicit was resolved:
scala> foo(".")
res0: Int = 666
但是,我实际上想要的是Implicits1.good
,而不是Implicits2.bad
.
But, I actually wanted Implicits1.good
, not Implicits2.bad
.
som-snytt和Shadowlands向我介绍了如何处理通配符导入-通配符导入,然后隐藏特殊隐式?.
som-snytt and Shadowlands educated me on how to handle wildcard imports - Wildcard Import, then Hide Particular Implicit?.
但是,我可以在编译时指定允许或禁止特定的隐式吗?
However, can I specify at compile-time that particular implicits are allowed or forbidden?
推荐答案
在REPL中进行测试会产生错误的结果.如果两个导入都在一个文件中,则会得到一个模棱两可的隐式错误.除此之外
Testing this in REPL will give wrong results. If you had both imports in a file, you'd get an ambiguous implicit error. Beyond this
我可以在编译时指定允许特定的隐式
can I specify at compile-time that particular implicits are allowed
导入它们.
或禁止
不导入它们.如果
两个对象都有多个我想使用的有用导入
both objects have multiple, useful imports that I want to use
然后您可以说导入所有内容除了这些特定的标识符" :
import Implicits2.{bad => _, bad2 => _, _}
如果已将隐式对象引入作用域,则禁用该对象的唯一方法是通过阴影处理,如链接的问题中所述.
If you have brought an implicit into scope, the only way to disable it is by shadowing, as in the linked question.
这篇关于在编译时指定合法隐含和/或非法隐含?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!