1. 简单匹配
object Test{
def main(args: Array[String]): Unit = {
val sex = -1
val res = sex match {
case 1 => "man"
case 2 => "women"
// case _ => "Not Allowed!" // other
case unexcepted => unexcepted + " is Not Allowed!"
}
println(res)
}
}
//-1 is Not Allowed!
或
val sex = -1
sex match {
case 1 => println("man")
case 2 => println("women")
case _ => println(sex + " is Not Allowed!")
}
2. 类型匹配
object Test{
def main(args: Array[String]): Unit = {
for(e <- List(9, 12.3, "spark", "hadoop", 'Hello)){
val res = e match {
case _: Int => e + " is a int value."
case _: Double => e + " is a double value."
case "spark" => e
case _: String => e + " is a string value."
case _ => e + " is unknown."
}
println(res)
}
}
}
// 9 is a int value.
// 12.3 is a double value.
// spark.
// hadoop is a string value.
// Hello is unknown.
3. 守卫(guard)语句
object Test{
def main(args: Array[String]): Unit = {
for(e <- List(1, 2, 3)){
e match {
case _ if(e%2 == 0) => println(e + " 是偶数")
case _ => println(e + " 是奇数")
}
}
}
}
// 1 是奇数
// 2 是偶数
// 3 是奇数
4. for 表达式中的模式
遍历过程中得到的每个值,都会被绑定到k和v两个变量上。
object Test{
val map = Map("one"->1, "two"->2, "three"->3)
def main(args: Array[String]): Unit = {
for((k,v) <- map){
println(k + ": " + v)
}
}
}
5. case 类的匹配
case类是一种特殊的类,它们经过优化以被用于模式匹配。
object Test{
case class Car(brand: String, price: Int)
val bmwCar = new Car("bmw", 100)
val bydCar = new Car("byd", 80)
val wlCar = new Car("wl", 90)
def main(args: Array[String]): Unit = {
for(e <- List(bmwCar, bydCar, wlCar)){
e match {
case Car("bmw", 100) => println("This is bmw car")
case Car("byd", 80) => println("This is byd car")
case Car(brand, price) => println("This is other car")
}
}
}
}
// This is bmw car
// This is byd car
// This is other car
6. Option 类型
标准类库中的Option类型用case类来表示那种可能存在、也可能不存在的值。Scala中当预计到变量或者函数返回值可能不会引用任何值的时候,建议你使用Option 类型。
Option 类包含一个子类Some,当存在可以被引用的值的时候,就可以使用Some来包含这个值,例如Some("Hadoop")。而None则被声明为一个对象,而不是一个类,表示没有值。
scala> val map = Map("one"->1, "two"->2, "three"->3)
map: scala.collection.immutable.Map[String,Int] = Map(one -> 1, two -> 2, three -> 3)
scala> map.get("two")
res0: Option[Int] = Some(2)
scala> map.get("five")
res1: Option[Int] = None
getOrElse()在这个Option是Some的实例时返回对应的值,而在是None的实例时返回传入的参数。
scala> val map = Map("one"->1, "two"->("21","22","23"), "three"->3)
map: scala.collection.immutable.Map[String,Any] = Map(one -> 1, two -> (21,22,23), three -> 3)
scala> val e = map.get("two")
e: Option[Any] = Some((21,22,23))
scala> val e = map.get("five")
e: Option[Any] = None
scala> e.getOrElse("no such number!")
res3: Any = no such number!
Option[T]实际上就是一个容器,可以把它看作一个集合,且这个集合中要么只包含一个元素(被包装在Some中返回),要么就不存在元素(返回None)。