Implementing classes in Scala from traits with the same method signature

by 10/18/2012 09:01:00 PM 0 comments
I just saw this exchange on the scala-user mailing list and thought I'd better make a note of it. It's easier to show rather than explain:
trait A {
  def f = "A.f"
}

trait B {
  def f = "B.f"
}
Doing the following doesn't work:
object C extends A with B

error: overriding method f in trait A of type => java.lang.String;
 method f in trait B of type => java.lang.String needs `override' modifier
       object D extends A with B
However, the following works:
object C extends A with B {
  override def f = super[A].f
}

scala> C.f
res6: java.lang.String = A.f
Or, if you want to use B's implementation:
object D extends A with B {
  override def f = super[B].f
}

scala> D.f
res7: java.lang.String = B.f

hohonuuli

Developer

Cras justo odio, dapibus ac facilisis in, egestas eget quam. Curabitur blandit tempus porttitor. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

0 comments: