9

Is it possible to unimport an implicit from the repl?

Say I do something like this,

scala> import scala.math.BigInt._
import scala.math.BigInt._

scala> :implicits
/* 2 implicit members imported from scala.math.BigInt */
  /* 2 defined in scala.math.BigInt */
  implicit def int2bigInt(i: Int): scala.math.BigInt
  implicit def long2bigInt(l: Long): scala.math.BigInt

And then decide that it was all a big mistake. How can I remove those implicits from the current scope?

My current technique is aborting the REPL and then starting a new one, I'm keen to avoid repeating it.

Dan Midwood
  • 18,694
  • 7
  • 33
  • 32

1 Answers1

13

You can hide an implicit by creating another implicit with the same name. Fortunately (for this case, anyway), rather than having an overloaded implicit, the new one displaces the old one:

scala> import language.implicitConversions
import language.implicitConversions

scala> def needsBoolean(b: Boolean) = !b
needsBoolean: (b: Boolean)Boolean

scala> implicit def int2bool(i: Int) = i==0
int2bool: (i: Int)Boolean

scala> val dangerous = needsBoolean(0)
dangerous: Boolean = false

scala> trait ThatWasABadIdea
defined trait ThatWasABadIdea

scala> implicit def int2bool(ack: ThatWasABadIdea) = ack
int2bool: (ack: ThatWasABadIdea)ThatWasABadIdea

scala> val safe = needsBoolean(0)
<console>:14: error: type mismatch;
 found   : Int(0)
 required: Boolean
       val safe = needsBoolean(0)
Rex Kerr
  • 166,841
  • 26
  • 322
  • 407
  • Ha. Nice. I guess this means unimport isn't possible. Instead of adding a trait I got the same with benefit with `implicit def int2bool = Unit` – Dan Midwood Mar 23 '13 at 23:19
  • @DanMidwood - You probably mean `implicit def int2bool = ()`, though my point is really that _anything_ works. I made a new trait to be sure that whatever was implicitly supplied wouldn't be wanted anywhere. (`= Unit` means "return the companion object to the `Unit` type; the unique `Unit` value, `()`, might possibly be implicitly wanted somewhere, but it's less likely that the companion object would be wanted.) – Rex Kerr Mar 23 '13 at 23:44
  • You're right. I was aiming for () and not for the companion object. My real aim was to have something that won't match anything, but now I'm less sure about my assumptions about Unit to have faith in that. I've got a lot of learning to do, thanks for your help – Dan Midwood Mar 23 '13 at 23:55
  • @DanMidwood - Creating a new trait--`IJustMadeThisUp` or whatever--that you don't use is the safest way to be sure it's not going to match anything anywhere! – Rex Kerr Mar 24 '13 at 00:16