function definition:
def f(): Int = try return 1 finally return 2
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, so 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.
11.1
while ((line = readLine()) != "") // This doesn't work!
println("Read: " + line)
When you compile this code, Scala will give you a warning that comparing values of type Unitand String using != will always yield true. Whereas in Java, assignment results in the value assigned (in this case a line from the standard input), in Scala assignment always results in the unit value, (). Thus, the value of the assignment "line = readLine()" will always be () and never be "". As a result, this while loop's condition will never be false, and the loop will, therefore, never terminate.
11.4
class Dollars(val amount: Int) extends AnyVal {
override def toString() = "$" + amount
}
As described in Section 10.6, the val prefix allows the amount parameter to be accessed as a field.
12.1
In fact, you can
do anything in a trait definition that you can do in a class definition, and the syntax looks exactly the same, with only two exceptions.
First, a trait cannot have any "class" parameters (i.e., parameters passed to the primary constructor of a class). In other words, although you could define a class like this:
class Point(x: Int, y: Int)
The following attempt to define a trait would not compile:
trait NoPoint(x: Int, y: Int) // Does not compile
You'll find out in Section 20.5 how to work around this restriction.
网友评论