scala: no common ancestors available for asInstanceOf []
source link: https://www.codesd.com/item/scala-no-common-ancestors-available-for-asinstanceof.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
scala: no common ancestors available for asInstanceOf []
I created some case classes used as messages in akka. When the program receives some messages, it calls the method asInstanceOf[]
, but I don't know what to put inside the brackets, as the message can be one of the 3 differents case classes.
here is a try :
abstract class Retour
case class Naissance(val sender : ActorRef) extends Retour
case class NaissanceEtMort(val sender : ActorRef) extends Retour
case class PlusUnMoisOK(val sender : ActorRef) extends Retour
but at the execution of my program I get this error message:
lapins.Clapier$PlusUnMoisOK$ cannot be cast to lapins.Clapier$Retour
can you help me?
EDIT:
the line of the error is those with [Retour] in :
val future = ask(couple,PlusUnMois)
val result = Await.result(future,timeout.duration).asInstanceOf[Retour]
and the error is below:
[ERROR] [07/02/2015 01:33:48.436] [clapier-akka.actor.default-dispatcher-5] [akka://clapier/user/$a] lapins.Clapier$PlusUnMoisOK$ cannot be cast to lapins.Clapier$Retour
akka.actor.ActorInitializationException: exception during creation
EDIT2:
resolved! the message sending was incorrectly written : indeed, I wrote "sender ! PlusUnMoisOK" instead of "sender ! PlusUnMoisOK(self)"
With:
ask(couple,PlusUnMois)
You are sending the class PlusUnMois
as a message. If you are doing the same in your couple
actor Await.result
is returning the class PlusUnMois
not an object of PlusUnMois
. Trying to cast the class PlusUnMois
to Retour
results to an error. Try sending an instance of PlusUnMois
, like:
val future = ask(couple,new PlusUnMois(someActorRef))
The same should be done in your couple
actor:
sender ! new PlusUnMois(someOtherActorRef)
Moreover, instead of using asInstanceOf
consider using pattern matching:
Await.result(future,timeout.duration) match {
case m : Naissance => // do something Naissance
case m : NaissanceEtMort => // do something NaissanceEtMort
case m : PlusUnMoisOK => // do something PlusUnMoisOK
}
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK