Control structures
Similarly to the majority of modern programming languages, the Scala language has a bunch of control structures; for example, for branching and looping. The control structures in question are if
, while
, for
, and pattern matching.
If and While
if
and while
are implemented the same way as they are in any other programming language:
scala> val flag = true flag: Boolean = true scala> if (flag) { | println("Flag is true") | } Flag is true scala> if (!flag) { | println("Flag is false") | } else { | println("Flag is true") | } Flag is true scala> var x: Int = 0 x: Int = 0 scala> while (x < 5) { | x += 1 | println(s"x = $x") | } x = 1 x = 2 x = 3 x = 4 x = 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 this expression. There are certain exceptions to this rule, however.
For
The for
statement is a little bit more unconventional. In fact, the for
statement is syntactic sugar for an application of the foreach
, map
, and flatMap
methods. For example, take a look at the following expression:
scala> val list = 0 to 3 list: scala.collection.immutable.Range.Inclusive = Range 0 to 3 scala> val result = | for { | e <- list | list2 = 0 to e | e2 <- list2 | } yield (e, e2) result: scala.collection.immutable.IndexedSeq[(Int, Int)] = Vector((0,0), (1,0), (1,1), (2,0), (2,1), (2,2), (3,0), (3,1), (3,2), (3,3)) scala> println(result.mkString("\n")) (0,0) (1,0) (1,1) (2,0) (2,1) (2,2) (3,0)
(3,1) (3,2) (3,3)
The preceding for
expression expands to the following method applications:
scala> val result = list.flatMap { e => | val list2 = 0 to e | list2.map { e2 => (e, e2) } | } result: scala.collection.immutable.IndexedSeq[(Int, Int)] = Vector((0,0), (1,0), (1,1), (2,0), (2,1), (2,2), (3,0), (3,1), (3,2), (3,3))
So, basically, if a type defines the methods specified in the preceding code, you can write the application in terms of the for
construct. For example, if you take an Option
type that defines map
, flatMap
, and foreach
, you can write a program as follows:
scala> val opt1 = Some(3) opt1: Some[Int] = Some(3) scala> val opt2 = Some(2) opt2: Some[Int] = Some(2) scala> val opt3: Option[Int] = None opt3: Option[Int] = None scala> val res1 = | for { | e1 <- opt1 | e2 <- opt2 | } yield e1 * e2 res1: Option[Int] = Some(6) scala> val res2 = | for { | e1 <- opt1 | e3 <- opt3 | } yield e1 * e3 res2: Option[Int] = None
The for
construct is not called a loop in Scala, but a Monadic flow. This is due to the special meaning of the map
and flatMap
functions in functional programming.
Pattern matching
Special constructs in Scala are partial functions and pattern matching. For example, you can write expressions as follows:
scala> val str = "Foo" str: String = Foo scala> str match { | case "Bar" => println("It is a bar") | case "Foo" => println("It is a foo") | } It is a foo
More complex pattern matching is also possible. For example, given a list, we can match on its head and tail, or its head and its second argument and its tail:
scala> val list = List(1, 2, 3, 4, 5) list: List[Int] = List(1, 2, 3, 4, 5) scala> list match { | case e1 :: e2 :: rest => e1 + e2 | } <console>:13: warning: match may not be exhaustive. It would fail on the following inputs: List(_), Nil list match { ^ res10: Int = 3
In fact, we can perform pattern matching on virtually anything with the help of so-called extractors. For example, it is possible to match on a custom data type as follows:
scala> class Dummy(x: Int) { val xSquared = x * x } defined class Dummy scala> object square { | def unapply(d: Dummy): Option[Int] = Some(d.xSquared) | } defined object square scala> new Dummy(3) match { | case square(s) => println(s"Square is $s") | } Square is 9
The semantics of pattern matching is that on runtime, the environment will call the unapply
function on the data type in question, and see whether this function returns some result or whether it is a None
. If some result is returned in an option, the result is used to populate the variables in the pattern matching clause. Otherwise, the pattern is considered not matched.
Partial functions
The preceding pattern matching statements are very close to the notion of partial functions in Scala. The same way pattern matching statements have a certain domain of cases that they can handle and throw an exception in all other cases, partial functions are defined on a part of their input domain. For example, the preceding match
statement can be converted into a partial function, as follows:
scala> val findSquare: PartialFunction[Any, Int] = { | case x: Int => x * x | case square(s) => s | } findSquare: PartialFunction[Any,Int] = <function1> scala> findSquare(2) res12: Int = 4 scala> findSquare(new Dummy(3)) res13: Int = 9 scala> findSquare("Stuff") scala.MatchError: Stuff (of class java.lang.String) at scala.PartialFunction$$anon$1.apply(PartialFunction.scala:255) at scala.PartialFunction$$anon$1.apply(PartialFunction.scala:253) at $anonfun$1.applyOrElse(<console>:13) at scala.runtime.AbstractPartialFunction.apply(AbstractPartialFunction.scala:34) ... 28 elided