How to override an implicit value?

2019-03-30 01:14发布

Suppose I have the code:

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
}

I get the error:

<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

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).

Another solution is to not do import X._, again something I'm trying to avoid.

3条回答
淡お忘
2楼-- · 2019-03-30 01:32

I agree with the other answer that explicitly providing the implicit in these types of situations is preferred, but if you insist on wanting to 'downgrade' the other implicit so it's no longer treated as an implicit then it is actually possible:

class A(implicit s:String = "foo"){println(s)}

object X {
  implicit val s1 = "hello"
}
object Y {
  import X._
  val s1 = X.s1 //downgrade to non-implicit

  // do something with X
  implicit val s2 = "hi"
  val a = new A
}

Again, this is a bit hackish, but it works.

查看更多
趁早两清
3楼-- · 2019-03-30 01:33

Another thing you can do is to import everything but s1: import X.{s1 => _, _}.

查看更多
戒情不戒烟
4楼-- · 2019-03-30 01:46

Try:

new A()(s2)

This should override the implicit parameter through er explicitly providing it.

查看更多
登录 后发表回答