Search code examples
scalatraitssubtypeabstract-type

Scala related trait, abstract types


I have 2 related traits. Dao will be used be a class and DaoHelper will be used by Dao's companion object. I would like trait Dao to be able use functions defined in DaoHelper, the only way I could figure out how to do this is to define the companion trait as a val. However somehow companion expects its type to be D.this.T which I thought I has defined as a subtype of Doa. I am confused here. My apologies for the newb question, I come from a dynamic language background.

/test2.scala:14: overriding value companion in trait Dao of type Test.DaoHelper[D.this.T]; [error] value companion has incompatible type [error] val companion = D

object Test extends App {

  trait Dao {
    type T <: Dao
    val companion: DaoHelper[T]
    def getHelpfulData = companion.help
  }

  trait DaoHelper[Dao] {
    val help = "Some helpful data"
  }

  class D extends Dao {
    val companion = D
  }

  object D extends DaoHelper[D]
}

Solution

  • companion has type DaoHelper[T], but T isn't specified anywhere in D, so how would the compiler know it is supposed to be D in class D? You can fix it by overriding it in D.

    class D extends Dao {
      type T = D
      val companion = D
    }