The Artima Developer Community
Sponsored Link

Java Buzz Forum
Lazy Functions With Scala

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Sam Newman

Posts: 800
Nickname: padark
Registered: Feb, 2004

Sam Newman is quite lazy
Lazy Functions With Scala Posted: Jun 4, 2009 1:53 PM
Reply to this message Reply

This post originated from an RSS feed registered with Java Buzz by Sam Newman.
Original Post: Lazy Functions With Scala
Feed Title: magpiebrain
Feed URL: http://feeds.feedburner.com/Magpiebrain
Feed Description: A Java Blog
Latest Java Buzz Posts
Latest Java Buzz Posts by Sam Newman
Latest Posts From magpiebrain

Advertisement

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.

Read: Lazy Functions With Scala

Topic: SaaS goes green with Hara to reduce cost and better energy efficiency Previous Topic   Next Topic Topic: Java Performance News May 2009

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use