9

是否可以从 repl 中取消导入隐式?

说我做这样的事情,

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

然后决定这都是一个大错误。如何从当前范围中删除这些隐式?

我目前的技术是中止 REPL,然后开始一个新的,我很想避免重复它。

4

1 回答 1

13

您可以通过创建另一个具有相同名称的隐式来隐藏隐式。幸运的是(对于这种情况,无论如何),新的不是重载的隐式,而是取代旧的:

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)
于 2013-03-23T21:51:51.193 回答