August 2018
Intermediate to advanced
380 pages
10h 2m
English
if and while are implemented the same way as they are in any other programming language:
scala> val flag = trueflag: Boolean = truescala> if (flag) { | println("Flag is true") | }Flag is truescala> if (!flag) { | println("Flag is false") | } else { | println("Flag is true") | }Flag is truescala> var x: Int = 0x: Int = 0scala> while (x < 5) { | x += 1 | println(s"x = $x") | }x = 1x = 2x = 3x = 4x = 5
Notice that in such constructs, you can optionally omit the curly braces if the body of the construct is a single expression:
scala> if (flag) println("Flag is true")Flag is true
This is something you can do in many places in Scala. Wherever you have a body that consists of a single expression, you can omit the curly braces around ...