第二章 控制结构和函数

2.1 条件表达式
if(x > 0)  1 else -1
val s = if(x > 0) 1 else -1


混合型表达式:
if(x>0) "positive" else -1


2.2 语句终止
val n = 12
if(n>0) { r = r * n; n -= 1}
s = s0 + (v - v0) * t + 0.5 * (a-a0) * t * t


if(n > 0){
 r = r * n
 n -= 1
}


2.3 块表达式和赋值
val distance = { val dx = x - x0; val dy = y - y0; sqrt(dx * dx + dy * dy)}
{ r = r * n; n -= 1}


2.4 输入和输出
print("Answer: ")
println(42)
println("Answer: " + 42)
println("Hello,%s! You are %d years old.\n","Fred",42)


val name = readLine("Your name: ")
print("Your age: ")
val age = readInt()
printf("Hello, %s! Next year,your will be %d.\n",name,age + 1)


2.5 循环
while(n > 0){
    r = r * n
    n -= 1
}




2.6 高级for循环和for推导式
for(i <- 1 to 3; j <- 1 to 3) print((10 * i + j) + " ")
for(i <- -1 to 3;j <- 1 to 3 if i != j) print((10 * i + j) + " ")
for(i <- 1 to 3; from = 4 - i;j <- from to 3) print((10 * i + j) + " ")
for(i <- 1 to 10 yield i % 3)
for(c <- "Hello"; i<- 0 to 1) yield (c + i).toChar
for(i <- 0 to 1;c <- "Hello") yield (c + i).toChar


for{  i<- 1 to 3
      from = 4 -i
      j <- from to 3
}


2.7 函数
def abs(x: Double) = if(x >= 0) x else -x
def fac(n: Int) = {
    var r =1
    for(i <- 1 to n) r = r * i
    r
}


对于递归函数,我们必须指定返回类型。例如:
def fac(n: Int): Int = if (n <= 0) 1 else n * fac(n - 1)


2.8 默认参数和带名参数
def decorate(str: String,left: String = "[",right: String = "]") = left + str + right
decorate(left = "<<<",str = "Hello", right = ">>>")
decorate("Hello",right = "]<<<")


2.9 变长参数
def sum(args: Int*) = {
    var result = 0
    for(arg <- args) result += arg
    result
}
val s = sum(1,4,9,16,25)


val s = sum(1 to 5)


val s = sum(1 to 5: _*)


def recursiveSum(args: Int*): Int = {
    if(args.length == 0) 0
    else args.head + recursiveSum(args.tail: _*)
}


val str = MessageFormat.format("The answer to {0} is {1}")
2.10 过程
Scala 对于不返回值的函数有特殊的表示法。如果函数体包含在花括号当中但没有前面的=号,那么返回类型就是Unit。这样的函数被称做过程(procedure)。过程不返回值,我们调用它仅仅是为了它的副作用。举例来说,如下过程把一个字符串打印在一个框中,就像这样:
--------
|hello|
--------
由于过程不返回任何值,所以我们可以略去=号
def box(s: String){
    var border = "-" * s.length + "--\n"
    println(border + "|" + s + "|\n" + border)
}


显示声明Unit返回类型
def box(s: String): Unit={
    var border = "-" * s.length + "--\n"
    println(border + "|" + s + "|\n" + border)
}


2.11 懒值
当val被声明为lazy时,它的初始化将被推迟,直到我们首次对它取值。例如,
lazy val words = scala.io.Source.fromFile("/usr/share/dict/words").mkString
懒值对于开销较大的初始化语句而言十分有用。它们还可以应对其他初始化问题,比如循环依赖。
你可以把懒值当做是介于val和def的中间状态。对比如下定义:
//在worlds被定义时被取值
val words = scala.io.Source.fromFile("/usr/share/dict/words").mkString
//在words被首次使用时取值
lazy val words = scala.io.Source.fromFile("/usr/share/dict/words").mkString
//在每一次words被使用时取值
def words = scala.io.Source.fromFile("/usr/share/dict/words").mkString


2.12 异常
Scala异常工作机制和Java或C++一样
throws new IllegalArgumentException("x should not be negative")


if(x >= 0){
    sqrt(x)
} else throw new IllegalArgumentException("x should not be negative")


捕获异常的语法采用的是模式匹配
try{
    process(new URL("http://horstmann.com/fred-tiny.gif"))
} catch{
    case _: MalformedURLException => println("Bad URL:" + url)
    case ex: IOException => ex.printStackTrace()
}


var in = new URL("http://horstman.com/fred.gif").openStream()
try{
    process(in)
} finally {
    in.close()
}


try{...} catch{...} finally{...}
try{try{...} catch{...}} finally {...}

你可能感兴趣的:(第二章 控制结构和函数)