Type of if
The result type of if (cond) expr
is the common base type of expr
and Unit
, just like if (cond) { expr } else { () }
See What is return type of if
statement? for details.
How to get Unit
To get an instance of type Unit
you should use ()
literal:
if (zoom > 50) g.setPaintColour(ColourInt.white)
()
Unit
value is the companion object of type Unit
. It's not an instance of type Unit
. Type of object Unit
is Unit.type
.
Do not use return
in lambda
The result of lambda is the result of the last statement in lambda body, so you could just add result value (in this case literal ()
) as the last line.
return
in lambda will return from the surrounding method rather than from the lambda itself using exception (NonLocalReturnControl
).
It's useful for java-style methods like this:
def firstNegative(seq: Seq[Int]): Option[Int] = {
for {
i <- seq
} if (i < 0) return Some(i)
return None
}
if (i < 0) return Some(i)
here is lambda body. Equivalent code for this method:
def firstNegative(seq: Seq[Int]): Option[Int] = {
seq.foreach{ i =>
if (i < 0) return Some(i)
}
return None
}