Specifying Legal and/or Illegal Implicits at Compile-time?

ⅰ亾dé卋堺 提交于 2019-12-11 16:29:23

问题


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

Then, given 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._

Running foo(".") on the REPL shows that Implicits2.bad's implicit was resolved:

scala> foo(".")
res0: Int = 666

But, I actually wanted Implicits1.good, not Implicits2.bad.

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?


回答1:


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

Import them.

or forbidden

Don't import them. If

both objects have multiple, useful imports that I want to use

then you can say "import everything except these specific identifiers":

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.



来源:https://stackoverflow.com/questions/32680854/specifying-legal-and-or-illegal-implicits-at-compile-time

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!