这是我在scala中发现的并且它有效并且我无法弄清楚为什么,有人可以解释为什么这有效吗?
基本上我可以使用val的引用,而我仍在定义它(因为我的其他对象/ actor将其作为参数接受)
val backbone: ActorRef = context.actorOf(
F_BackBone.props(
context.actorOf(F_PictureHandler.props(backbone)),
context.actorOf(F_UserHandler.props(backbone)),
context.actorOf(F_PageProfileHandler.props(backbone))
)
)
如果我没有明确定义类型,我将收到编译器错误,这是有道理的。
答案 0 :(得分:2)
请注意,在这种特定情况下,虽然代码编译,但它不会正常运行,因为正如在另一个答案的评论中所建议的那样,传递给其他actor的backbone
的值是' null& #39 ;.
此示例演示了这一点:
import akka.actor.{Props, Actor, ActorRef, ActorSystem}
class SenderReceiver(sendTo:ActorRef) extends Actor{
override def preStart(): Unit = {
self ! "Start"
}
def receive = {
case "Start" => sendTo ! "Hello"
case "Hello" => println("Received Hello")
}
}
object SenderReceiver {
def props(sendTo:ActorRef):Props = Props(new SenderReceiver(sendTo))
}
object Example extends App {
val system = ActorSystem()
val actor: ActorRef = system.actorOf(SenderReceiver.props(actor))
system.awaitTermination()
}
这会产生以下结果(反复出现,因为主管策略试图重新启动actor):
[info] [ERROR] [12/01/2015 09:47:04.543] [default-akka.actor.default-dispatcher-9] [akka://default/user/$a] null
[info] java.lang.NullPointerException
[info] at SenderReceiver$$anonfun$receive$1.applyOrElse(example.scala:10)
[info] at akka.actor.Actor$class.aroundReceive(Actor.scala:467)
[info] at SenderReceiver.aroundReceive(example.scala:3)
[info] at akka.actor.ActorCell.receiveMessage(ActorCell.scala:516)
[info] at akka.actor.ActorCell.invoke(ActorCell.scala:487)
[info] at akka.dispatch.Mailbox.processMailbox(Mailbox.scala:238)
[info] at akka.dispatch.Mailbox.run(Mailbox.scala:220)
[info] at akka.dispatch.ForkJoinExecutorConfigurator$AkkaForkJoinTask.exec(AbstractDispatcher.scala:397)
[info] at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
[info] at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
[info] at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
[info] at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)
答案 1 :(得分:1)
在函数式编程语言中,递归定义是一个重要的概念。想想定义阶乘的经典例子。
对于Scala的具体案例,本月早些时候在一篇文章中给出了一个非常好的解释: A variable used in its own definition?