有没有办法获得特征的隐式清单

时间:2014-10-03 14:22:08

标签: scala akka

我正在尝试实现一个覆盖Actor的特征,以拦截某个消息类型,如下所示:

trait MyTrait[M] extends Actor {

    abstract override def receive = {

            case msg: M => 
                // Do Something
                super.receive(msg)
        }
    }

这给了我编译器警告:

abstract type pattern M is unchecked since it is eliminated by erasure

我无法传递隐式类清单,因为它是一个特征,而不是一个类。有没有办法在仍然使用特征的同时实现上述目标?

1 个答案:

答案 0 :(得分:5)

您可以为特征添加抽象定义并在以后实施:

scala> trait T[A] {
    implicit def ev: Manifest[A]
    def r: Any => Int = { case a: A => 1 case _ => 0}
  }
defined trait T

scala> class X(implicit val ev: Manifest[String]) extends T[String]
defined class X

scala> new X().r("")
res0: Int = 1

scala> new X().r(5)
res1: Int = 0