scala中没有switch,但是有case,其case相当强大,有各种不同的匹配方式。
一.简单匹配,值匹配:
例 a:
val bools = List(true, false) for (bool <- bools) { bool match { case true => println("heads") case false => println("tails") case _ => println("something other than heads or tails (yikes!)") } }
例 b:
import scala.util.Random val randomInt = new Random().nextInt(10) randomInt match { case 7 => println("lucky seven!") case otherNumber => println("boo, got boring ol' " + otherNumber) }
二. 类型匹配
例a:
val sundries = List(23, "Hello", 8.5, 'q') for (sundry <- sundries) { sundry match { case i: Int => println("got an Integer: " + i) case s: String => println("got a String: " + s) case f: Double => println("got a Double: " + f)