scalacake-pattern

Scala Generic Subtypes and Cake Pattern


I have the following class hierarchy:

  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)

Now I have the following trait:

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

Now I would like to extend this trait for students and teachers:

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

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

Now I would like to to create Handler class which take cars for all type of events:

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

Now when I try to create Handler for some type of Event, I'm getting compilation error:

val studentHandler = new Handler with StudentAction

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

What am I missing?


Solution

  • Handler type had to be parametrized too:

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