Copyright © Cay S. Horstmann 2015
if
expression has a value: if (x > 0) 1 else -1Like
x > 0 ? 1 : -1
in Java/C/C++.
if (x > 0) "positive" else -1 // Type is Any
Unit
type is similar to void
, but it has one value, denoted ()
.else
has value Unit
:
if (x > 0) 1is the same as
if (x > 0) 1 else ()
val distance = { val dx = x - x0 val dy = y - y0 sqrt(dx * dx + dy * dy) }
()
:
while (n > 0) { i += 1 n = n / 2 }
for (i = 1; i <= n; i++)
.for (i <- 1 to n)(Note: No
val
/var
before i
)for (ch <- "Hello"
for (i <- 1 to 3; j <- 1 to 3) print((10 * i + j) + " ")
for (i <- 1 to 3; j <- 1 to 3 if i != j) print((10 * i + j) + " ")
for (i <- 1 to 10) yield i % 3
def abs(x: Double) = if (x >= 0) x else -x
def fac(n: Int): Int = if (n <= 0) 1 else n * fac(n - 1)
=
, the function doesn't return a value:
def box(s: String) { // Look carefully: no = val border = "-" * s.length + "--\n" println(border + "|" + s + "|\n" + border) }
=
symbol:
def fac(n: Int) { // Probably an error var r = 1 for (i <- 1 to n) r = r * i r }
regionMatches(ignoreCase =
true, ...)
def decorate(str: String, left: String = "[", right: String = "]") = left + str + right
left
and right
:
decorate("Hello") // [Hello]
right
:
decorate("Hello", ">>>[") // >>>[Hello]
left
, named parameter for right
:
decorate("Hello", right = "]<<<") // [Hello]<<<
*
after type:
def sum(args: Int*) = { // args is a Seq[Int] var result = 0 for (arg <- args) result += arg result }
val s = sum(1, 4, 9, 16, 25)
Seq[Int]
, need decoration to pass it:
val s = sum(1 to 5: _*)
def recursiveSum(args: Int*): Int = { if (args.length == 0) 0 else args.head + recursiveSum(args.tail : _*) }
aeiou
).
def isVowel(ch: Char) = ...
if
statement? If so, write it without an if
. (Hint: contains
)isVowel
. Use a for
loop.
def vowels(s: String) = ...
for ... yield
loop. (Hint: Guards)while
loop.vowelChars
with default "aeiuo"
and a parameter ignoreCase
with default true
."Übeltätergehör"
. (Yes, those things with dots are vowels in German.)