ВУЗ: Не указан
Категория: Не указан
Дисциплина: Не указана
Добавлен: 02.01.2026
Просмотров: 3477
Скачиваний: 0
Section 7.5 |
Chapter 7 · Built-in Control Structures |
173 |
import java.net.URL
import java.net.MalformedURLException
def urlFor(path: String) = try {
new URL(path)
}catch {
case e: MalformedURLException =>
new URL("http://www.scala-lang.org")
}
Listing 7.13 · A catch clause that yields a value.
calling f() results in 2. By contrast, given:
def g(): Int = try { 1 } finally { 2 }
calling g() results in 1. Both of these functions exhibit behavior that could surprise most programmers, thus it’s usually best to avoid returning values from finally clauses. The best way to think of finally clauses is as a way to ensure some side effect happens, such as closing an open file.
7.5Match expressions
Scala’s match expression lets you select from a number of alternatives, just like switch statements in other languages. In general a match expression lets you select using arbitrary patterns, which will be described in Chapter 15. The general form can wait. For now, just consider using match to select among a number of alternatives.
As an example, the script in Listing 7.14 reads a food name from the argument list and prints a companion to that food. This match expression examines firstArg, which has been set to the first argument out of the argument list. If it is the string "salt", it prints "pepper", while if it is the string "chips", it prints "salsa", and so on. The default case is specified with an underscore (_), a wildcard symbol frequently used in Scala as a placeholder for a completely unknown value.
There are a few important differences from Java’s switch statement. One is that any kind of constant, as well as other things, can be used in
Cover · Overview · Contents · Discuss · Suggest · Glossary · Index
Section 7.5 |
Chapter 7 · Built-in Control Structures |
174 |
val firstArg = if (args.length > 0) args(0) else ""
firstArg match {
case "salt" => println("pepper") case "chips" => println("salsa") case "eggs" => println("bacon") case _ => println("huh?")
}
Listing 7.14 · A match expression with side effects.
cases in Scala, not just the integer-type and enum constants of Java’s case statements. In Listing 7.14, the alternatives are strings. Another difference is that there are no breaks at the end of each alternative. Instead the break is implicit, and there is no fall through from one alternative to the next. The common case—not falling through—becomes shorter, and a source of errors is avoided because programmers can no longer fall through by accident.
The most significant difference from Java’s switch, however, may be that match expressions result in a value. In the previous example, each alternative in the match expression prints out a value. It would work just as well to yield the value rather than printing it, as shown in Listing 7.15. The value that results from this match expression is stored in the friend variable. Aside from the code getting shorter (in number of tokens, anyway), the code now disentangles two separate concerns: first it chooses a food, and then it prints it.
val firstArg = if (!args.isEmpty) args(0) else ""
val friend = firstArg match {
case "salt" => "pepper" case "chips" => "salsa" case "eggs" => "bacon" case _ => "huh?"
}
println(friend)
Listing 7.15 · A match expression that yields a value.
Cover · Overview · Contents · Discuss · Suggest · Glossary · Index
Section 7.6 |
Chapter 7 · Built-in Control Structures |
175 |
7.6Living without break and continue
You may have noticed that there has been no mention of break or continue. Scala leaves out these commands because they do not mesh well with function literals, a feature described in the next chapter. It is clear what continue means inside a while loop, but what would it mean inside a function literal? While Scala supports both imperative and functional styles of programming, in this case it leans slightly towards functional programming in exchange for simplifying the language. Do not worry, though. There are many ways to program without break and continue, and if you take advantage of function literals, those alternatives can often be shorter than the original code.
The simplest approach is to replace every continue by an if and every break by a boolean variable. The boolean variable indicates whether the enclosing while loop should continue. For example, suppose you are searching through an argument list for a string that ends with “.scala” but does not start with a hyphen. In Java you could—if you were quite fond of while loops, break, and continue—write the following:
int i |
= |
0; |
// This is Java |
boolean |
foundIt = false; |
|
|
while |
(i < args.length) { |
|
|
if (args[i].startsWith("-")) { |
|||
i |
= |
i + 1; |
|
continue; |
|
||
}
if (args[i].endsWith(".scala")) { foundIt = true;
break;
}
i = i + 1;
}
To transliterate this Java code directly to Scala, instead of doing an if and then a continue, you could write an if that surrounds the entire remainder of the while loop. To get rid of the break, you would normally add a boolean variable indicating whether to keep going, but in this case you can reuse foundIt. Using both of these tricks, the code ends up looking as shown in Listing 7.16.
Cover · Overview · Contents · Discuss · Suggest · Glossary · Index
Section 7.6 |
Chapter 7 · Built-in Control Structures |
176 |
var i = 0
var foundIt = false
while (i < args.length && !foundIt) { if (!args(i).startsWith("-")) {
if (args(i).endsWith(".scala")) foundIt = true
}
i = i + 1
}
Listing 7.16 · Looping without break or continue.
This Scala code in Listing 7.16 is quite similar to the original Java code. All the basic pieces are still there and in the same order. There are two reassignable variables and a while loop. Inside the loop, there is a test that i is less than args.length, a check for "-", and a check for ".scala".
If you wanted to get rid of the vars in Listing 7.16, one approach you could try is to rewrite the loop as a recursive function. You could, for example, define a searchFrom function that takes an integer as an input, searches forward from there, and then returns the index of the desired argument. Using this technique the code would look as shown in Listing 7.17:
def searchFrom(i: Int): Int = if (i >= args.length) -1
else if (args(i).startsWith("-")) searchFrom(i + 1) else if (args(i).endsWith(".scala")) i
else searchFrom(i + 1)
val i = searchFrom(0)
Listing 7.17 · A recursive alternative to looping with vars.
The version in Listing 7.17 gives a human-meaningful name to what the function does, and it uses recursion to substitute for looping. Each continue is replaced by a recursive call with i + 1 as the argument, effectively skipping to the next integer. Many people find this style of programming easier to understand, once they get used to the recursion.
Cover · Overview · Contents · Discuss · Suggest · Glossary · Index
Section 7.7 |
Chapter 7 · Built-in Control Structures |
177 |
Note
The Scala compiler will not actually emit a recursive function for the code shown in Listing 7.17. Because all of the recursive calls are in tail-call position, the compiler will generate code similar to a while loop. Each recursive call will be implemented as a jump back to the beginning of the function. Tail-call optimization will be discussed in Section 8.9.
If after all this discussion you still feel the need to use break, there’s help in Scala’s standard library. Class Breaks in package scala.util.control offers a break method, which can be used to exit the an enclosing block that’s marked with breakable. Here an example how this library-supplied break method could be applied:
import scala.util.control.Breaks._ import java.io._
val in = new BufferedReader(new InputStreamReader(System.in))
breakable { while (true) {
println("? ")
if (in.readLine() == "") break
}
}
This will repeatedly read non-empty lines from the standard input. Once the user enters an empty line, control flow exits from the enclosing breakable, and with it the while loop.
The Breaks 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.7Variable scope
Now that you’ve seen Scala’s built-in control structures, we’ll use them in this section to explain how scoping works in Scala.
Cover · Overview · Contents · Discuss · Suggest · Glossary · Index
Section 7.7 |
Chapter 7 · Built-in Control Structures |
178 |
Fast track for Java programmers
If you’re a Java programmer, you’ll find that Scala’s scoping rules are almost identical to Java’s. One difference between Java and Scala exists, however, in that Scala allows you to define variables of the same name in nested scopes. If you’re a Java programmer, therefore, you may wish to at least skim this section.
Variable declarations in Scala programs have a scope that defines where you can use the name. The most common example of scoping is that curly braces generally introduce a new scope, so anything defined inside curly braces leaves scope after the final closing brace.3 As an illustration, consider the function shown in Listing 7.18.
The printMultiTable function shown in Listing 7.18 prints out a multiplication table.4 The first statement of this function introduces a variable named i and initializes it to the integer 1. You can then use the name i for the remainder of the function.
The next statement in printMultiTable is a while loop:
while (i <= 10) {
var j = 1
...
}
You can use i here because it is still in scope. In the first statement inside that while loop, you introduce another variable, this time named j, and again initialize it to 1. Because the variable j was defined inside the open curly brace of the while loop, it can be used only within that while loop. If you were to attempt to do something with j after the closing curly brace of this while loop, after the comment that says j, prod, and k are out of scope, your program would not compile.
All variables defined in this example—i, j, prod, and k—are local variables. Such variables are “local” to the function in which they are defined. Each time a function is invoked, a new set of its local variables is used.
3There are a few exceptions to this rule, because in Scala you can sometimes use curly braces in place of parentheses. One example of this kind of curly-brace use is the alternative for expression syntax described in Section 7.3.
4The printMultiTable function shown in Listing 7.18 is written in an imperative style. We’ll refactor it into a functional style in the next section.
Cover · Overview · Contents · Discuss · Suggest · Glossary · Index
Section 7.7 |
Chapter 7 · Built-in Control Structures |
179 |
def printMultiTable() {
var i = 1
// only i in scope here while (i <= 10) {
var j = 1
// both i and j in scope here while (j <= 10) {
val prod = (i * j).toString
// i, j, and prod in scope here
var k = prod.length
// i, j, prod, and k in scope here
while (k < 4) { print(" ")
k += 1
}
print(prod) j += 1
}
// i and j still in scope; prod and k out of scope
println() i += 1
}
// i still in scope; j, prod, and k out of scope
}
Listing 7.18 · Variable scoping when printing a multiplication table.
Cover · Overview · Contents · Discuss · Suggest · Glossary · Index
Section 7.7 |
Chapter 7 · Built-in Control Structures |
180 |
Once a variable is defined, you can’t define a new variable with the same name in the same scope. For example, the following script with two variables named a in the same scope would not compile:
val a = 1
val a = 2 // Does not compile println(a)
You can, on the other hand, define a variable in an inner scope that has the same name as a variable in an outer scope. The following script would compile and run:
val a = 1;
{
val a = 2 // Compiles just fine println(a)
}
println(a)
When executed, the script shown previously would print 2 then 1, because the a defined inside the curly braces is a different variable, which is in scope only until the closing curly brace.5 One difference to note between Scala and Java is that unlike Scala, Java will not let you create a variable in an inner scope that has the same name as a variable in an outer scope. In a Scala program, an inner variable is said to shadow a like-named outer variable, because the outer variable becomes invisible in the inner scope.
You might have already noticed something that looks like shadowing in the interpreter:
scala> val a = 1 a: Int = 1
scala> val a = 2 a: Int = 2
scala> println(a) 2
5By the way, the semicolon is required in this case after the first definition of a because Scala’s semicolon inference mechanism will not place one there.
Cover · Overview · Contents · Discuss · Suggest · Glossary · Index