npiv
npiv

Reputation: 1837

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

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?

Upvotes: 11

Views: 3181

Answers (1)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340873

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().

Upvotes: 21

Related Questions