Scala 泛型子类型和蛋糕模式

Scala Generic Subtypes and Cake Pattern

我有以下 class 层次结构:

  abstract class Event(val timeStamp:Long,val id:Long ) 
  case class StudentEvent(override val timeStamp:Long, override val id:Long, 
      firstName:String,lastName:String) extends Event(timeStamp,id )
  case class TeacherEvent(override val timeStamp:Long, override val id:Long, 
      firstName:String,lastName:String.....) extends Event(timeStamp,id)

现在我有以下特点:

trait Action[T <: Event] {
  def act[T](event:T)
}

现在我想为学生和老师扩展这个特性:

trait StudentAction extends Action[StudentEvent]{
   def act(event:StudentEvent) = println(event)
}

trait TeacherAction extends Action[TeacherEvent]{
   def act(event:TeacherEvent) = println(event)
}

现在我想创建 Handler class,它可以为所有类型的活动安排汽车:

class Handler{
  self:Action[Event] =>
  def handle(event:Event) = act(event)
}

现在,当我尝试为某种类型的事件创建处理程序时,出现编译错误:

val studentHandler = new Handler with StudentAction

illegal inheritance; self-type Handler with StudentAction does not conform to Handler's selftype Handler 
 with Action[Event]

我错过了什么?

处理程序类型也必须参数化:

scala> class Handler[T<:Event] {
     | self:Action[T] =>
     | def handle(event:T) = act(event)
     | }
defined class Handler

@Ashalynd 是正确的。投票了。 还将继承逻辑提取到更纯净的代码中,如下所示:

class PARENT
class CHILD extends PARENT


trait A[T <: PARENT]
trait AA extends A[CHILD]

class B[T <: PARENT] {
  self: A[T] => 

}

val b = new B[CHILD]() with AA