September 2018
Intermediate to advanced
398 pages
9h 43m
English
In Scala, if (condition) ifExpr else if ifExpr2 else elseExpr is an expression, and has a type. If all sub-expressions have a type A, the type of the if ... else expression will be A as well:
scala> def agePeriod(age: Int): String = { if (age >= 65) "elderly" else if (age >= 40 && age < 65) "middle aged" else if (age >= 18 && age < 40) "young adult" else "child"}agePeriod: (age: Int)String
If sub-expressions have different types, the compiler will infer a common super-type, or widen the type if it is a numeric type:
scala> val ifElseWiden = if (true) 2: Int else 2.0: DoubleifElseWiden: Double = 2.0scala> val ifElseSupertype = if (true) 2 else "2"ifElseSupertype: Any = 2
In the first expression present in the preceding ...
Read now
Unlock full access