Self-binding val value during definition in scala

This is what I learned in scala and it works, and I can’t understand why, can anyone explain why this works?

Essentially, I can use the val reference while I still define it (because my other objects / actors take it as a parameter)

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)) ) ) 

I will get a compiler error if I do not explicitly define the type, which makes sense.

+5
source share
2 answers

Please note that in this particular case, although the code compiles, it will not behave correctly, because, as suggested in the comments to another answer, the backbone value passed to other participants is null.

This example demonstrates this:

 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() } 

This gives the following (repeatedly, as the supervisor strategy tries to restart the 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
source

In functional programming languages, recursive definitions are an important concept. Consider, for example, the classic example of factorial definition.

For a specific Scala case, a very good explanation was given in a post earlier this month: Variable used in its own definition?

+1
source

Source: https://habr.com/ru/post/1237032/


All Articles