Syntax |
Comments in Scala look like in Java and C: Everything after a double-slash // up to the end of the line is a comment. A long comment that continues over several lines can be written by enclosing it in /* and */.
Programming languages allow you to group together statements into blocks. For instance, the body of a function, or the body of a while-loop is a block. In Python, this so-called block structure is indicated using indentation. Python is very much an exception: in nearly all programming languages, indentation, and in fact any white space, does not matter at all. In Scala, like in Java and C, block structure is indicated using braces: { and }. For example, a typical while-loop may look like this:
var i = 0 while (i <= 10) { printf("%3d: %d\n", i, i * i) i += 1 }
Like in C, C++, and Java, a block in Scala is either a single statement, or a sequence of statements surrounded by braces. So you do not need to use braces when your block consists of only one statement. For example, the following conditional statement
if (numIceCreams > 13) { println("Happiness is having enough ice cream") }can be abbreviated to
if (numIceCreams > 13) println("Happiness is having enough ice cream")Do this only if it makes the code easier to read, not harder!
Note that in Scala you should put the opening brace of a block on the same line with the def, if, or while keyword. This may be different from what you are used to do in C.
Like in Python, you do not need to terminate statements in Scala. But if you want to put several statements on the same line, you have to separate them using semicolons:
val s = "hello"; println(s)
The syntax of the conditional expression is
if (pts > 80) { s = "well done!" } else { s = "practice harder" }As in Python, the else part can be omitted:
if (pts > 80) { println("good student") }
So far, Scala's if statement looks exactly like in Java or C. There is a difference though: Scala's if expression has a value itself, and so you can write code like this:
val msg = if (pts > 80) "well done" else "practice harder!"You can therefore use if expressions inside other expressions.
Scala's while loop looks exactly like Java's or C's (and much like Python's):
var i = 1 while (i < 10) { println(i + "\t: " + i*i) i += 1 }Scala does not have break and continue statements. (You will find this annoying, but you may understand why later in the course.)
The simple while loop above could have been written more easily using a for loop as follows:
for (i <- 1 until 10) println(i + "\t: " + i*i)Here i until j includes the integers \(\{i, i+1, \ldots, j-1\}\). Note that curly braces are not needed since there is only one statement inside the loop.
Alternatively, you could have written
for (i <- 1 to 10) println(i + "\t: " + i*i)This time, the loop goes from 1 to 10, as i to j includes the integers \(\{i, i+1, \ldots, j\}\).
Syntax |