4
votes

I understand how scala addresses the diamond inheritance situation by considering the order of the traits mentioned. I am curious to understand how it solves the same issue for fields. Here is what I am trying to understand -

class A {print("A")}
trait B extends A {print("B") ; val x="b"}
trait C extends B {print("C")}
trait D extends A {print("D");  val x="d"}

object TraitsEx extends App {
  var d = new A with B with D
  println(d.x)
}

The above code does not compile.

2
Doesn't the error message say how to fix it? - Jasper-M
Could you also paste the compilation error here, please? - WarFox

2 Answers

4
votes

Well not magically as you can see. If this was a property of A class, then you could override it - with class linearization, you already know, each with X, where X extends A would override values:

trait A {
  val x = "a"
}

trait B extends A {
  override val x = "b"
}

trait C extends A {
  override val x = "c"
}

object Main {
  def main(args: Array[String]): Unit = {
    println((new A {}).x)
    println((new A with B).x)
    println((new A with B with C).x)
  }
}

prints

a
b
c

However, when each class introduces its own x that compiler cannot prove to override other xs, then it will leave solving that problem to you. It also suggest one solution:

object TraitsEx extends App {
  var d = new A with B with D { override val x = "d" }
  println(d.x)
}

this way you would override all different xs and remove ambiguity.

2
votes

Scala solves conflicting fields by making you solve it.

Error:(21, 16) <$anon: A$A123.this.A with A$A123.this.B with A$A123.this.D> inherits conflicting members:
  value x in trait B of type String  and
  value x in trait D of type String
(Note: this can be resolved by declaring an override in <$anon: A$A123.this.A with A$A123.this.B with A$A123.this.D>.)
  var d = new A with B with D
              ^

If one field is supposed to override the other than you are required to put that in the code. Without a specified override the compiler won't make any decisions for you.