Built-in Control Structures

  • The only control structors in Scala are if, while, for, try, match, and function calls
  • if: val filename = if (args.nonEmpty) args(0) else “default_filename”
  • while loop: there are two types:
while (a != 0) {
    val temp = a
    a = b % a
    b = temp

do {
    line = readLine()
    println("Read: "+ line)
} while (line != "")
  • for loop: the for expression syntax works for any kind of collection, not just arrays. There are many ways to use a for loop:
//simple loop
val filesHere = (new java.io.File(".")).listFiles
for (file <- filesHere)

//this adds filtering to the for loop
for (file <- filesHere if file.getName.endsWith(".scala"))

//it’s possible to have multiple conditions
for (
    file <- filesHere
    if file.isFile
    if file.getName.endsWith(".scala")
) println(file)

//nested iteration
def fileLines(file: java.io.File) = scala.io.Source.fromFile(file)

def grep(pattern: String) =
    for (
        file <- filesHere
        if file.getName.endsWith(".scala");
        line <- fileLines(file)
        if line.trim.matches(pattern)
) println(file +": "+ line.trim)


//mid-steram variable bindings
def grep(pattern: String) =
    for {
        file <- filesHere
        if file.getName.endsWith(".scala")
        line <- fileLines(file)
        trimmed = line.trim
        if trimmed.matches(pattern)
    } println(file +": "+ trimmed)


//producing a new collection
/*this will assemble a collection of Scala files. The type of the 
resulting collection is based on the kind of collections 
processed in the iteration clauses. In this case the result is an 
Array[File], because filesHere is an array and the type of the yielded 
expression is File.*/

def scalaFiles =
    for (
        file <- filesHere
        if file.getName.endsWith(“.scala”)
    ) yield file
  • throwing exceptions: e.g. throw new RuntimeException(“n must be even”). In this example, one branch of an if computes a value, while the other throws an exception and computes Nothing. The type of the whole if expression is then the type of that branch which does compute something.
  • try/catch expressions: example:
try {
    val f = new FileReader(“filename.txt”)
} catch {
    catch ex: FileNotFoundException =>
    catch ex: IOException =>
  • finally clause: you can wrap an expression in a finally clause if you want to cause some code to execute no matter how the expression terminates. e.g.:
val f = new FileReader(“input.txt)
    try {
    } finally {
  • match expression: is like switch statement. The default is specified using an underscore (_). There’s no break keyword, as there is no fall through from one alternative to the next. Big difference to Java/PHP, is that match results in a value e.g.:
val input = args(0)
    input match {
        case “salt” => println(“pepper”)
        case _ => println(“type salt!”)

//Same as:

val result = input match {
    case “salt” => “pepper"
    case _ => println(“type salt!”)

println (result)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s