如何从 Scala repl 中取消导入隐式? [英] How can an implicit be unimported from the Scala repl?

查看:47
本文介绍了如何从 Scala repl 中取消导入隐式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to unimport an implicit from the 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

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

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

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

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

推荐答案

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

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)

这篇关于如何从 Scala repl 中取消导入隐式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆