开发者

How does 'self' work in Scala actors?

开发者 https://www.devze.com 2023-04-06 12:26 出处:网络
The following code snippet is taken from Programming in Scala import actors.Actor object NameResolver extends Actor {

The following code snippet is taken from Programming in Scala

import actors.Actor

object NameResolver extends Actor {

 import java.net.{InetAddress, UnknownHostException}


 def act() {
   react {
     case (name: String, actor: Actor) =>
       actor ! getIp(name)
       act()
     case "EXIT" =>
       println("Name resolver exiting.")
     // quit
     case msg =>
       println("Unhandled message: " + msg)
       act()
   }
 }

 def getIp(name: String): Option[InetAddress] = {
   try {
     Some(InetAddress.getByName(name))
   } catch {
     case _: UnknownHostException => None
   }
 }
}

Firstly within react {} what does the recursive call to act() do? It looks like all the cases would fail and it will simply drop through to the end doing nothing.

Secondly in the book, they use the following REPL example

Na开发者_StackOverflowmeResolver ! ("www.scala-lang.org", self)

Where does 'self' come from? I have tried to replicate this in a main method

 def main(args: Array[String]) {
   NameResolver.start()
   NameResolver ! ("www.scala-lang.org", Actor.self)
 }

The above does not work


  1. act() runs recursively, unless you send an EXIT message. For any other message that neither match EXIT nor (name: String, actor: Actor), case msg will be used. In other words case msg is a kind of a generic handler that processes all the unmatched messages.

  2. Actor.self is a reliable way to refer to the actor instance from within an actor's body (it's recommended to use self instead of this, to refer to the right instance). In your case, you're calling Actor.self not from an actor, and, thus, it fails.


  1. The code inside react is called only when a new message is available. Thus, if you call recursively act() inside a case clause, the actor will "wait" until a new message is sent (without blocking a thread). It's an alternative to loop when you want to change the behavior of the actor according to what it received. Here you stop waiting for messages when you get "EXIT".

  2. self is supposed to be used inside an actor everytime you want to use this.

0

精彩评论

暂无评论...
验证码 换一张
取 消