I'm working my way through Bruce Tate's Seven Languages in Seven Weeks and am having a hard time understanding his implementation of sizer.scala
(Scala: Day 3). In particular, consider the following Singleton object
object PageLoader {
def getPageSize(url : String) = Source.fromURL(url).mkString.length
}
and the following method that, using actors, calculates the number of characters in each web page given by the urls
array.
def getPageSizeConcurrently() = {
val caller = self
for(url <- urls) {
actor { caller ! (url, PageLoader.getPageSize(url)) }
}
for(i <- 1 to urls.size) {
receive {
case (url, size) =>
println("Size for " + url + ": " + size)
}
}
}
getPageSizeConcurrently
? Is it possible for self to refer to a function?getPageSizeConcurrently
, is this considered to be pretty standard in the Scala world? Why send messages to a function instead of an object, or vice versa?UPDATE: The code in question only uses self once, but it does start with the following import
statements.
import scala.io._
import scala.actors._
import Actor._
Looking through the Scala API, it appears that the Actor
singleton object has a self
method. Even if that's the self
assigned to caller
, though, I don't see why the receive
block would be executed.
There is a self method on the Actor companion object. From the scaladoc:
Returns the currently executing actor. Should be used instead of this in all blocks of code executed by actors.
I'm guessing that your code has imported the Actor object, and that it is the self method on the Actor object your code is calling. This way you get a reference to the main actor thread you're in, and the anonymous actors you start to get page size can send the message back to the thread you're in.
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