简体   繁体   中英

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

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM