Scala通用子类型和蛋糕模式

时间:2015-01-08 13:59:44

标签: scala cake-pattern

我有以下类层次结构:

  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 Handler{
  self:Action[Event] =>
  def handle(event:Event) = act(event)
}

现在,当我尝试为某种类型的事件创建Handler时,我收到了编译错误:

val studentHandler = new Handler with StudentAction

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

我错过了什么?

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

@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