在函数定义中使用scala泛型

时间:2014-03-12 16:24:39

标签: scala

我想建立一个方便的功能来制作akka演员:

 def makeActor[T](id: Int): ActorRef =
   system.actorOf(Props(classOf[T], id, updater), "entity" + id)

 makeActor[SomeActor](1) ! "Some Message"

但是这表示"类型需要,但T发现n#34;。这段代码出了什么问题?

3 个答案:

答案 0 :(得分:3)

使用scala反射,例如:

import scala.reflect._

def spawn[T <: Actor: ClassTag](id: Int) = system.actorOf(Props(classTag[T].runtimeClass, ...), s"entity$id")

答案 1 :(得分:2)

答案可以在这里找到:Scala classOf for type parameter

您可以编写代码,例如:

def makeActor[T](id: Int)(implicit ev: Manifest[T]): ActorRef = system.actorOf(Props(ev.erasure, id, updater), "entity" + id)

答案 2 :(得分:2)

完全正常的例子:

import akka.actor.{ActorSystem, Props, Actor, ActorRef}
import scala.reflect.ClassTag

object TestActor extends App {

  val system: ActorSystem = ActorSystem("rest-service-actor-system")

  def makeActor[T <: Actor : ClassTag](id: Int): ActorRef =
    system.actorOf(Props(implicitly[ClassTag[T]].runtimeClass), "entity" + id)

  class A extends Actor {
    override def receive = {
      case anything => println("A GOT MESSAGE: " + anything)
    }
  }

  class B extends Actor {
    override def receive = {
      case anything => println("B GOT MESSAGE: " + anything)
    }
  }

  makeActor[A](1) ! "hello"
  makeActor[A](2) ! "bye"

  system.shutdown()
}

通常打印:

A GOT MESSAGE: bye
A GOT MESSAGE: hello

它会强制您拥有一个同样为Actor的类型。例如,此代码将无法编译:

class C

makeActor[C](3)
你得到的错误是:

type arguments [TestActor.C] do not conform to method makeActor's type parameter bounds [T <: akka.actor.Actor]
  makeActor[C](3)
           ^