Scala学习笔记(五):内建控制循环
前言
Scala中内建控制循环包括if、while、for、try、match和函数调用。
if和while与java类似,不做介绍。
for
基础用法
def main(args: Array[String]): Unit = {
val intArr = Array(1, 2, 3)
for (i <- intArr) {
println(i)
}
}
过滤
for语句块中可以添加if判断,用来达到过滤元素的效果
for(i <- 1 to 20 if i % 3 == 0) {
println(i)
}
if可以多次使用
for (i <- 1 to 20 if i % 3 == 0 if i % 2 != 0) {
println(i)
}
生成新集合
使用yield,会记住每一次迭代,并最终收集生成新集合
val inclusive = (1 to 20).toList
val ints: List[Int] = for (i <- inclusive if i % 3 == 0 if i % 2 != 0) yield i
println(ints)
使用try表达式处理异常
抛出异常
try{
val f = new FileReader("input.txt")
} catch {
case ex: FileNotFoundException => // 丢失文件异常
case ex: IOException => // IO异常
}
match
val firstArg = if (args.length > 0) args(0) else ""
firstArg match {
case "hello" => println("hello")
case "world" => println("world")
case _ => println("Hello World!")
}
match还可以产生值
val firstArg = if (args.length > 0) args(0) else ""
val friend = firstArg match {
case "hello" => "Hello"
case "world" => "World"
case _ => "Hello World!"
}
println(friend)
God, Grant me the SERENITY, to accept the things I cannot change,
COURAGE to change the things I can, and the WISDOM to know the difference.