How to override an implicit value?

空扰寡人 提交于 2019-12-03 16:09:43

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

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.

Try:

new A()(s2)

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

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