Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"=>" operator in Scala

Tags:

scala

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?

like image 751
Sayat Satybald Avatar asked Jul 14 '14 09:07

Sayat Satybald


3 Answers

it's passing parameter by name. means expression will be evaluated when parameter is accessed.

like image 115
wedens Avatar answered Nov 16 '22 01:11

wedens


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.

like image 29
Rahul Tripathi Avatar answered Nov 16 '22 00:11

Rahul Tripathi


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.

like image 37
Jim Collins Avatar answered Nov 15 '22 23:11

Jim Collins