How can an implicit be unimported from the Scala repl?

前提是你 提交于 2021-01-27 04:02:02

问题


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.


回答1:


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)


来源:https://stackoverflow.com/questions/15592324/how-can-an-implicit-be-unimported-from-the-scala-repl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!