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)
}
}
}
- What does self refer to?
getPageSizeConcurrently? Is it possible for self to refer to a function? - Assuming that self does refer to
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:
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.