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?
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With