如何覆盖隐式值? [英] How to override an implicit value?
本文介绍了如何覆盖隐式值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有代码:
class A(implicit s:String = "foo"){println(s)}
object X {
implicit val s1 = "hello"
}
object Y {
import X._
// do something with X
implicit val s2 = "hi"
val a = new A
}
我得到了错误:
<console>:14: error: ambiguous implicit values:
both value s2 in object Y of type => String
and value s1 in object X of type => String
match expected type String
val a = new A
有什么办法可以告诉Scala在Y
中使用值s2
?
(如果我将s2
重命名为s1
,它可以按预期工作,但这不是我想要的.)
Is there any way I can tell Scala to use the value s2
in Y
?
(if I rename s2
to s1
, it works as expected but that is not what I want).
另一种解决方案是不执行import X._
,这也是我试图避免的事情.
Another solution is to not do import X._
, again something I'm trying to avoid.
推荐答案
您可以做的另一件事是导入除s1
:import X.{s1 => _, _}
之外的所有内容.
Another thing you can do is to import everything but s1
: import X.{s1 => _, _}
.
这篇关于如何覆盖隐式值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文