Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending messages to functions in Scala

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

like image 475
Chris Frederick Avatar asked Jul 19 '11 06:07

Chris Frederick


1 Answers

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.

like image 187
Jostein Stuhaug Avatar answered Oct 07 '22 03:10

Jostein Stuhaug