Could you please explain why the following code is not working as expected.
The actor is not printing the message
Thanks.
class Base {
def f() = { "This is Base" }
}
class Sub extends Base {
override def f() = { "This is Sub" }
}
case class myCase(x: Base)
import scala.actors._
object myActor extends Actor {
def act()
{
loop {
react {
case myCase(x) => x.f()
case msg => "unknown"
}
}
}
def main(args: Array[String]): Unit = {
this ! myCase(new Base)
this ! myCase(new Sub)
}
}
Answering the question
The problem has nothing whatsoever to do with inheritance or case classes (I have re-titled the question to reflect this). The code does not print anything for two reasons:
Because your code does not actually make any calls to
println! Replace:with
Because you do not start your actor. I think your program would make more sense if the actor were an inner class:
Advice: case classes and inheritance
I would, however, offer the advice that using inheritance in the presence of case classes is a bad idea. I usually use the approach of declaring common behaviour/state in a trait:
Why is it a bad idea? Well, one of the contracts that case-classes give you is a rigid definition of equivalence (that is, an
equalsandhashCodeimplementation). In the presence of inheritance, this could well be misleading. That is, your code will probably not do what you expect. Consider the following;Now if I create 2 instances…
They are equivalent
But they do not have the same state
Note, I am not saying this is a bug. I’m just saying it’s an area where you might find that you introduce a bug in your code because you have made the assumption that any state of the case class is included in its equivalence.