I'm new to Scala and has searched over here but didn't find the answer. I'm wondering what is this operator mean "x: => Boolean" in argument context of the function.
package scala
abstract class Boolean {
def && (x: => Boolean): Boolean
def || (x: => Boolean): Boolean
}
I know that def example(x: Int => Boolean): Boolean
would mean anonymous function that takes Int and return Boolean. However, what it means if argument omitted?
it's passing parameter by name. means expression will be evaluated when parameter is accessed.
Its is referred as right arrow. It is also popluar by the name of "fat arrow"
The right arrow =>
separates the function’s argument list from its body.
Example:
object TimerAnonymous {
def oncePerSecond(callback: () => Unit) {
while (true) { callback(); Thread sleep 1000 }
}
def main(args: Array[String]) {
oncePerSecond(() =>
println("time flies like an arrow..."))
}
}
The presence of an anonymous function in this example is revealed by the right arrow => which separates the function’s argument list from its body. In this example, the argument list is empty, as witnessed by the empty pair of parenthesis on the left of the arrow. The body of the function is the same as the one of timeFlies above.
It is actually syntactic sugar for a zero parameter function call:
x: () => Boolean
And as such x is not evaluated until the function is called so we get lazy evaluation of the parameter.
Every time that x is referenced in the body of the method it is re-evaluated. If you do not want this to happen you can do the following:
lazy val a = x
Adding the lazy keyword to the decalaration ensures that x is only evaluated when 'a' is first referenced.
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