开发者

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]
}


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
}


I don't quite understand what you are trying to do with class D, but you are getting this error because you are assigning D to companion in class D, but companion has type DaoHelper[T] as defined in Dao. Since D has type Dao and Dao is not a subtype of DaoHelper[T], this will not work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜