一、for表达式
1、util与to的区别:
scala> for(i <- 1 to 4) print("#" + i)
//结果
#1#2#3#4
//使用until
scala>for(i <- 1 until 4) print("#" + i)
//结果
#2#3#4
上面例子比较了until和to的区别,在for循环枚举集合类或其他时,until是不包括上边界的值,而to上边界的值。
2、for循环的过滤:我们在java中对for循环时,如果需要过滤,我们一般是通过在for循环的主体内容中添加if语句来过滤,当然在scala中也可以这样,但scala支持直接在for后面循环体内添加过滤器,举个例子说明下:
val files = (new java.io.File(".")).listFiles //列出本目录下的所有文件
for(file <- files if file.getName.endsWith(".scala"))
println(file)
3、嵌套枚举:在java中一般都是针对for循环嵌套循环,scala中我们可以根据具体情况来嵌套多个枚举。举个例子:
def fileLines(file: java.io.File) =
scala.io.Source.fromFile(file).getLines.toList
def grep(partten:String) =
for {
file <- files //第一个循环枚举
if file.getName.endsWith(".scala")
line <- fileLines(file) //第二个循环枚举
trimmed = line.trim
if trimmed.matches(partten)
} println(file + ": " + trimmed)
二、try-catch-finally
scala中也有try-catch-finally的表达式,基本上和java中类似,下面主要说不通的地方,看个例子:
import java.io.FileReader
import java.io.FileNotFoundException
import java.io.IOException
try {
val f = FileReader("input.txt")
//其他操作,略
} catch {
case ex: FileNotFoundException => //错误操作信息描述
case ex: IOException => //错误操作信息描述
}
上面的try-catch表达式中明显与java不同的是,scala中只有一个catch子句,捕获的各种异常是通过catch中的case来捕获的。
三、match表达式
scala中match表达式相当于java中的switch表达式,这里就不重点描述了,举个例子说明下:
val firstArg = if (args.length > 0) args(0) else ""
firstArg match {
case "one" => println("one")
case "two" => println("two")
case "three" => println("three")
case _ => println("default")
}