Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can an implicit be unimported from the Scala repl?

Tags:

scala

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.

like image 402
Dan Midwood Avatar asked Mar 23 '13 21:03

Dan Midwood


1 Answers

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)
like image 60
Rex Kerr Avatar answered Nov 20 '22 14:11

Rex Kerr