Search code examples
scalainheritancemultiple-inheritance

Class Linearization not working in scala 2.13


I'm trying to upgrade scala 2.12 to scala 2.13.5

Class linearization is not properly working for me, IntelliJ and Scala compiler throws an error but ideally it should work. Below is the problem.

trait A[E] {
  def getObject: E = {
    // some implementation
  }
}

abstract class B[T](e: Object) {
  def getObject: T = {
    // some implemntation
  }
}

class C[T] extends B[T](null) with A[String] {
  
  def myMethod(): Unit = {
    println(this.getObject.someMethodWhichIsNotInStringClassButAvailableInTClass)
  }
}

In the above sample program as well, this.getObject is coming from A where I'm expecting it to come from B. Looks like my understanding is wrong. But need to understand this class linearization problem in detail.

Because of the above issue, my code is not compiling as the required method is not available in String class.

Also the same code compiles with scala 2.12 but not with scala 2.13.5.

Another reference - https://stackoverflow.com/a/49832570/819866


Solution

  • This should not compile at all ... and it indeed does not for me (2.13.1):

           error: class C inherits conflicting members:
             def getObject: T (defined in trait B) and
             def getObject: String (defined in trait A)
             (note: this can be resolved by declaring an `override` in class C.)
    

    You cannot inherit different methods with the same name.

    Also, if your inheritance was actually valid, linearization would still work left to right:

        trait A { def foo: Sting }
        trait B extends A { def foo = "b" }
        trait C extends A { def foo = "c" }
        class D extends B with C
    
        println(new D().foo)
    

    This prints "c".