下面的类在新的HelloWorld行引起错误:
Exception in thread "main" akka.actor.ActorInitializationException: You cannot create an instance of [HelloWorld] explicitly using the constructor (new). You have to use one of the 'actorOf' factory methods to create a new actor. See the documentation.
at akka.actor.ActorInitializationException$.apply(Actor.scala:219)
at akka.actor.Actor$class.$init$(Actor.scala:436)
at HelloWorld.<init>(HelloWorld.scala:4)
at Driver$.main(HelloWorld.scala:38)
at Driver.main(HelloWorld.scala)
所以我尝试:val hw = actorOf(new HelloWorld)
但这会导致编译器错误:
not found: value actorOf
以下HelloWorld应如何实施?
读取其他Scala文档时,需要在扩展Actor的类中定义act方法,然后在此类上调用start方法,是否有理由使用actorOf而不是定义act方法?
以下课程摘自Scala akka docs http://doc.akka.io/docs/akka/2.2.0/scala.html:
import akka.actor.Actor
import akka.actor.Actor._
import akka.actor.Props
class HelloWorld extends Actor {
override def preStart(): Unit = {
// create the greeter actor
val greeter = context.actorOf(Props[Greeter], "greeter")
// tell it to perform the greeting
greeter ! Greeter.Greet
}
def receive = {
// when the greeter is done, stop this actor and with it the application
case Greeter.Done => context.stop(self)
}
object Greeter {
case object Greet
case object Done
}
class Greeter extends Actor {
def receive = {
case Greeter.Greet =>
println("Hello World!")
sender ! Greeter.Done
}
}
}
object Driver {
def main(args: Array[String]) {
new HelloWorld
}
}
答案 0 :(得分:8)
您需要编辑主页,如下所示。其次,在第5行中,您需要将其更改为context.actorOf(Props(new Greeter))
。这是因为您的Greeter
没有定义apply
函数,因此您需要自己手动创建Greeter对象。
以下工作代码:
import akka.actor.ActorSystem
class HelloWorld extends Actor {
override def preStart(): Unit = {
// create the greeter actor
val greeter = context.actorOf(Props(new Greeter), "greeter")//line 5
// tell it to perform the greeting
greeter ! Greeter.Greet
}
def receive = {
// when the greeter is done, stop this actor and with it the application
case Greeter.Done => context.stop(self)
}
object Greeter {
case object Greet
case object Done
}
class Greeter extends Actor {
def receive = {
case Greeter.Greet =>
println("Hello World!")
sender ! Greeter.Done
}
}
}
object Driver {
def main(args: Array[String]) {
val system = ActorSystem("Main")
val ac = system.actorOf(Props[HelloWorld])
}
}
答案 1 :(得分:4)
如果您想使用您的主类,请执行以下操作:
import akka.actor.{ActorSystem, Props}
object Driver extends App {
val system = ActorSystem("System")
val hw = system.actorOf(Props[HelloWorld], name = "hw")
}
这将创建一个新的actor系统,然后使用该actor系统创建HelloWorld actor。
您还可以按照akka说明操作: 将Akka.Main设置为主类,并将程序“com.example.HelloWorld”作为参数。
答案 2 :(得分:2)
val greeter = context.actorOf(Props(new Greeter), "greeter")//line 5
我认为你不需要为Greeter提供新的关键字。我相信道具已经为你做到了。如果有任何新的东西应该是