vnd
vnd

Reputation: 322

Override implicit vals from trait

I need overriding implicit in object res defing one from trait. The purpose is to define custom implicits in one place (trait B). Trait a is defined in external library. Is it possible?

trait t {
}

object m extends t
object q extends t

trait a {
  implicit val o: t = m
}

trait b {
  implicit val o: t = q
}

trait c {
  def action(implicit v: t): Unit  = {} 
}

object res extends c with a with b {
  //i need smth like override val o = super[b].o
  val ololo= action
}

Upvotes: 2

Views: 786

Answers (1)

Michael Zajac
Michael Zajac

Reputation: 55569

It is not possible to mix-in two unrelated traits that both contain a member with the same identifier. The Scala compiler has no way to resolve which one would take precedence in this scenario. Since types A and B are related, o does not even need to have the same type in both of them. Trait B needs to extend A and override o. There isn't any other way to override a member without using inheritance.

trait T
case object M extends T
case object Q extends T

trait A {
  implicit val o: T = M
}

trait B extends A {
  override implicit val o: T = Q
}

trait C {
  def action(implicit v: T): Unit = println(v)
}

object Res extends C with B {
    def call() = action
}

scala> Res.call()
Q

Since you are already mixing A into Res anyway, it is assumed that A is not difficult to extend, since Res must implement any other unmentioned abstract members.

Upvotes: 3

Related Questions