Preserving type arguments in Akka receive

情到浓时终转凉″ 提交于 2019-12-05 21:24:07

After fixing the error Event takes type parameters:

def receive = {
  case e: Event[_] =>
    if (e.ct.runtimeClass == classOf[Int])
      println("Got an Event[Int]!")
    else if (e.ct.runtimeClass == classOf[String])
      println("Got an Event[String]!")
    else
      println("Got some other Event!")
  case _ =>
    println("Got no Event at all!")
}

the code compiles. It can be slightly simplified by not looking inside the ClassTags (of course, the implementation of ClassTag#equals is going to compare the classes):

import scala.reflect.{ClassTag, classTag}

def receive = {
  case e: Event[_] =>
    if (e.ct == ClassTag.Int) // or classTag[Int]
      println("Got an Event[Int]!")
    else if (e.ct == classTag[String])
      println("Got an Event[String]!")
    else
      println("Got some other Event!")
  case _ =>
    println("Got no Event at all!")
}

You can also do pattern matching on the internal variable inside a nested class in which case it is more concise, you can utilise various pattern matching tricks and you don't even need ClassTag: eg

case class Event[T](t: T)    

def receive = {
  case Event(t: Int) => 
    println("Int")
  case Event((_: Float | _: Double)) => 
    println("Floating Point")
  case Event(_) =>
    println("Other")
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!