What does the (code: => Unit) parameter do in this scala function from the scala documentation:
def unless(exp: Boolean)(code: => Unit): Unit = if (!exp) code
unless(x < 5) {
println("x was not less than five")
}
What does the (code: => Unit) parameter do in this scala function from the scala documentation:
def unless(exp: Boolean)(code: => Unit): Unit = if (!exp) code
unless(x < 5) {
println("x was not less than five")
}
The =>
syntax inside of a function's parameter list means that that parameter is itself a function (known as a higher-order function). What that function signature is saying is that unless
is a function that takes a boolean, and take a function that takes no parameters and returns Unit
. Here are some more examples:
// This is a function that takes as a parameter that is a function that takes an Int, and returns a Boolean
def foobar(f: Int => Boolean) = ???
// It might be called like this:
foobar(i => i / 2 == 0)
// Which is the same as this
def isEven(i: Int): Boolean = {
i / 2 == 0
}
foobar(isEven)