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
NameResolver ! ("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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With