magpiebrain

The blog of Sam Newman. A Software Developer in London.

Lazy Functions With Scala

This tripped me up recently - I was passing in a function to be executed periodically by a java.util.Timer. The original code looked something like this:

def addTask(seconds: Int)(task: Unit) {
    val t = new TimerTask() {
    	def run = task
    }
    
    timer.scheduleAtFixedRate(t, 0, seconds * 1000);
  }

...

addTask(5) {
  println("Hello!")
}

The issue here is that when I called addTask, the function was run immediatley - the value of the function was getting passed in, not the function itself. The issue turned out to be the way I defined the function - ‘task: Unit’ executes the function and passes in the result to addTask. What I should of done is the following:

def addTask(seconds: Int)(task: => Unit) {
    val t = new TimerTask() {
    	def run = task
    }
    
    timer.scheduleAtFixedRate(t, 0, seconds * 1000);
  }

This actually passes the function, not the value of the function - that ‘=>’ is all important. The problem here is that both are valid scala - but the first really makes no sense in this context.

Comments (View)
blog comments powered by Disqus