2
votes

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?

2

2 Answers

2
votes

Handler type had to be parametrized too:

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

@Ashalynd is correct. up voted. also to extract the inherit logic into a purer code looks like this:

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