1

I recently stumbled into an abstract class with the following method :

abstract class Boolean {
    def && (x: => Boolean): Boolean = etc...
}

I was wondering what was the meaning of x: => Boolean ? does it mean that x can be of any type and it does produce a boolean ? or that is that x is of the type of the abstract class ?

thanks

Ismail H
  • 4,226
  • 2
  • 38
  • 61

2 Answers2

3

https://docs.scala-lang.org/tour/by-name-parameters.html

By-name parameters are only evaluated when used. They are in contrast to by-value parameters.

By-name parameters have the advantage that they are not evaluated if they aren’t used in the function body. On the other hand, by-value parameters have the advantage that they are evaluated only once.

nutic
  • 457
  • 2
  • 12
2

x is a by-name parameter, which means that it will be evaluated only when it is referenced in the method. In this case, it is being used to produce the short-circuiting behavior of the && method:

def foo(): Boolean = {
  println("In foo")
  true
}

true && foo()

If you run this in the REPL, you will never see "In foo" printed, since && doesn't need the result of foo.

You can think of by-name parameters as being similar to zero-argument functions, but more lightweight, and with slight differences in syntax:

def bar(x: () => Int): Unit // bar takes a function returning an Int
def baz(x: => Int): Unit // baz takes an Int as a by-name parameter
Brian McCutchon
  • 8,354
  • 3
  • 33
  • 45