In [2]:
val bools = Seq(true, false)
for (bool <- bools) {
bool match {
case true => println("Got heads")
case false => println("Got tails")
}
}
In [3]:
for {
x <- Seq(1, 2, 2.7, "one", "two", "four")
} {
var str = x match {
case 1 => "int 1"
case i: Int => "other int: " + i
case d: Double => "a double: " + x
case "one" => "string one"
case s: String => "other string: " + s
case unexpected => "unexpected value: "+ unexpected
}
println(str)
}
unexpected匹配任意输入,x的值被赋给unex这个变量。由于未给出任何类型说明,unexpected的类型被推断为Any,起到default语句的作用。
In [4]:
import scala.annotation.switch
In [5]:
val i = 1
val x = (i: @switch) match {
case 1 => "One"
case 2 => "Two"
case _ => "Other"
}
In [6]:
// 该情况使用scalac编译将报错
val i = 1
val Two = 2 // added
val x = (i: @switch) match {
case 1 => "One"
case Two => "Two" // replaced the '2'
case _ => "Other"
}
Scala使用tableswitch优化具有一定争议,不想@tailrec那么通用。tableswitch优化需要满足几个条件:
In [7]:
// 有时,我们也可以使用Map来代替简单的switch
val monthNumberToName = Map(
1 -> "January",
2 -> "February",
3 -> "March",
4 -> "April",
5 -> "May",
6 -> "June",
7 -> "July",
8 -> "August",
9 -> "September",
10 -> "October",
11 -> "November",
12 -> "December"
)
val monthName = monthNumberToName(4)
println(monthName) // prints "April"
In [8]:
def checkY(y: Int) = {
for {
x <- Seq(99, 100, 101)
} {
val str = x match {
case `y` => "found y!"
case i: Int => "int: " + i
}
println(str)
}
}
In [9]:
checkY(100)
在case子句中,以小写字母开头的标识符被认为是用来提取待匹配的新变量。如果需要引用之前已经定义的变量时,应使用反引号将其包围。
In [10]:
trait Command
case object Start extends Command
case object Go extends Command
case object Stop extends Command
case object Whoa extends Command
In [11]:
def executeCommand(cmd: Command) = cmd match {
case Start | Go => "start" // or use start()
case Stop | Whoa => "stop"
}
In [12]:
executeCommand(Stop)
In [14]:
case class Person(firstName: String, lastName: String)
case class Dog(name: String)
In [15]:
def echoWhatYouGaveMe(x: Any): String = x match {
// constant patterns
case 0 => "zero"
case true => "true"
case "hello" => "you said 'hello'"
case Nil => "an empty List"
// sequence patterns
case List(0, _, _) => "a three-element list with 0 as the first element"
case List(1, _*) => "a list beginning with 1, having any number of elements"
case Vector(1, _*) => "a vector starting with 1, having any number of elements"
// tuples
case (a, b) => s"got $a and $b"
case (a, b, c) => s"got $a, $b, and $c"
// constructor patterns
case Person(first, "Alexander") => s"found an Alexander, first name = $first"
case Dog("Suka") => "found a dog named Suka"
// typed patterns
case s: String => s"you gave me this string: $s"
case i: Int => s"thanks for the int: $i"
case f: Float => s"thanks for the float: $f"
case a: Array[Int] => s"an array of int: ${a.mkString(",")}"
case as: Array[String] => s"an array of strings: ${as.mkString(",")}"
case d: Dog => s"dog: ${d.name}"
case list: List[_] => s"thanks for the List: $list"
case m: Map[_, _] => m.toString
// the default wildcard pattern
case _ => "Unknown"
}
In [16]:
// trigger the constant patterns
println(echoWhatYouGaveMe(0))
println(echoWhatYouGaveMe(true))
println(echoWhatYouGaveMe("hello"))
println(echoWhatYouGaveMe(Nil))
// trigger the sequence patterns
println(echoWhatYouGaveMe(List(0,1,2)))
println(echoWhatYouGaveMe(List(1,2)))
println(echoWhatYouGaveMe(List(1,2,3)))
println(echoWhatYouGaveMe(Vector(1,2,3)))
// trigger the tuple patterns
println(echoWhatYouGaveMe((1,2))) // two element tuple
println(echoWhatYouGaveMe((1,2,3))) // three element tuple
// trigger the constructor patterns
println(echoWhatYouGaveMe(Person("Melissa", "Alexander")))
println(echoWhatYouGaveMe(Dog("Suka")))
// trigger the typed patterns
println(echoWhatYouGaveMe("Hello, world"))
println(echoWhatYouGaveMe(42))
println(echoWhatYouGaveMe(42F))
println(echoWhatYouGaveMe(Array(1,2,3)))
println(echoWhatYouGaveMe(Array("coffee", "apple pie")))
println(echoWhatYouGaveMe(Dog("Fido")))
println(echoWhatYouGaveMe(List("apple", "banana")))
println(echoWhatYouGaveMe(Map(1->"Al", 2->"Alexander")))
// trigger the wildcard pattern
println(echoWhatYouGaveMe("33d"))
In [ ]:
In [ ]:
In [ ]:
In [ ]: