Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Returning a void function with 0 parameters, ugly syntax?

Tags:

scala

Given a method defined as follows

 def descendEach(times:Int)(f:()=>Unit) {
      for (i <- 1 to times) {
          // other code
          f()
      }
   }

when I use this method I want to be able to write

 gd.descendEach(20){
    println(gd.cost)
 }

but the scala compiler only lets me get away with

  gd.descendEach(20){ () => 
    println(gd.cost)
 }

which is kind of ugly. Am I missing something here? Is it possible to write it in the first way I presented?

like image 945
npiv Avatar asked Oct 28 '11 19:10

npiv


1 Answers

Use the following syntax:

def descendEach[T](times:Int)(f: => T)

This way you can not only pass function without extra () => (this is called pass by name), but also use functions returning any type (not necessarily Unit). It is sometimes convenient when you have an existing function you want to pass but don't really care about its return value:

def g() = 42
descendEach(20)(g)

Note that with this syntax you are simply using f, not f().

like image 95
Tomasz Nurkiewicz Avatar answered Oct 26 '22 19:10

Tomasz Nurkiewicz