Kevin Meredith
Kevin Meredith

Reputation: 41909

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?

Upvotes: 0

Views: 92

Answers (1)

Alexey Romanov
Alexey Romanov

Reputation: 170713

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.

Upvotes: 2

Related Questions