Programming in Scala Gist 7

Vinu Charanya
vTechNotes
Published in
6 min readMay 25, 2016

These are the key points from the Programming in Scala, Second Edition by Martin Odersky, Lex Spoon, Bill Venners. I wanted to make note of some key points. They may seem broken and not make much sense, if you have not read the book. This is for personal reference. Feel free to correct me if I have interpreted anything wrong in this post.

Chapter 7 — Built in Control Structures

  • Scala has only a handful of built in control structures and they always result in some value.
  • This avoids the need to create temporary variables to hold this value.
  • This is a feature of a functional programming where programs are viewed as computing a value and hence components of a program should also compute a value.

7.1 If expression

  • Scala’s if is similar to other languages.
  • Since it returns a value, you can write an expression as

7.2 While and do-while Loops

  • While and do-while are again similar to other languages. They do not result in an interesting value.
  • Their return type is always Unit. The value and in fact the only value is called unit value and written as ().
  • In the above example, greet() does not have an = (equals) sign before the body and is defined a procedure with a Unit return type.
  • Reassignment to vars will always result in Unit (). For example comparing the result of res below yields true and warning states type Unit and Unit are compared.
  • Be suspicious about while and do-while loops as they mostly change values and are for side effects, try to avoid them if possible.

7.3 For loop

  • Similar to other languages, you can iterate through integers or collections
  • The format for(fruit -> fruits) read as fruit in fruits is called a generator
  • A generator expression generates a series of values in a for expression. For example, in for(i <1 to 10), the generator expression is “1 to 10”.
  • It also supports iterating through ranges like 1 to 10 or 1 until 10

Filering

  • Filter: An if followed by a boolean expression in a for expression. In for (i <- i to 10; if i%2 ==0), the filter is “if i % 2 == 0), the filter expression is the boolean expression “ i % 2 == 0”
  • You can add multiple filters in a for loop
  • If you add multiple <- clauses, it becomes nested loop.
  • Curly parentheses can also be used instead of braces. Scala compiler will not infer semicolons within parentheses.

Mid stream variable binding

  • Within a for loop, the result can be bound to a new variable using equals sign (=). The bound variable is introduced and used just like a val.

Producing a new collection

  • Using yield before the body block of the for loop, the values can be stored in a collection
  • Each time the body of the for expression executes, it produces one value and the result will included all of the yielded values in a single collection.

7.4 Exception handling with try expression

  • Similar to other languages. Method terminates by throwing an exception. The method’s called can either catch and handle the exception or simply terminate.

Throwing Exceptions and Catching Exceptions

  • Throwing an exception is similar to other languages like Java

throw new IllegalArgumentException

  • An expression throw has type nothing.
  • Scala’s catching exception syntax uses pattern matching for consistency.
  • The body is executed one by one till a match is found, if not try-catch will terminate and the exception will propagate.
  • Scala does not require you to catch checked exception or declare them in throw clause

The finally clause

  • finally clause will cause the enclosing code to execute no matter how the exception terminates.
  • File close is a good example of when to use finally.

Yielding a value

  • Scala try-catch-finally results in a value. The result is that of the try clause if no exception is thrown or the relevant catch clause if an exception is thrown and caught.
  • If an exception is thrown but not caught, the exception has no result at all.
  • The value computed in the finally clause, if there is one is dropped.
  • As in java, if a finally clause includes an explicit return statement or thrown an exception, that return value or exception will “overrule” any previous values that originated in the try block or one of its catch clauses.
  • In the above two methods, f() will return 2 and g() will return 1. The return statements make a difference.

7.5 Match expressions

  • Match expressions lets you select using arbitrary patterns and like other control statements it returns a value.
  • In the example below, the match expression is used to match the first arg based on case and perform the appropriate block
  • The default case is a specified field with an underscore (_), a wildcard symbol frequently used in Scala as a placeholder for a completely unknown value.
  • Few differences from Java’s switch stmt:
  • Any kind of constant and other things can be used in cases, not just the integer-type and enum constants
  • There are no breaks at the end of each alternative. It is implicit
  • There is not fall through and match expression results in a value.

7.6 Living without break and continue

  • Break and continue do not mesh well with function literals.
  • The simplest approach is to replace every continue by an if and every break by a boolean value. The boolean variable indicates whether the enclosing while loop should continue.
  • If you still need a break, Scala’s standard library has a class Breaks in package scala.util.control offers a break method. which can be used to exit the enclosing block that’s marked with breakable. Eg.,
  • The way the above works is the break class implements break by throwing an exception that is caught by an enclosing application of the breakable method.
  • Therefore, the call to break does not need to be in the same method as the call to breakable.

7.7 Variable scope

  • Scala and Java has almost the same scoping rules. One difference is, Scala allows you to define variables of the same name in nested scopes
  • Variables are local to the function in which they are defined. Each time a function is invoked, a new set of its local variable is used.
  • Once a variable is defined you can’t define a new variable with the same name in the same scope. You can define a variable in an inner scope that has the same name as a variable in an outer scope.

7.8 Refactoring imperative-style code

  • Avoid and refactor functions that print and instead return strings
  • Side effect free functions are easier to unit test
  • Avoid while loops and vars. Instead use helper functions
  • Helper function: A function that is often implemented as local function, whose purpose is to provide a service to one or more other functions nearby.

Conclusion

Scala’s built in structures are minimal, but they do the job and their tendency to return a value supports functional style.

--

--