Chap 14 模式匹配和样例类
focus on
match 表达式 是一个更好的 switch
没有模式匹配, 会抛出 MatchError。 可以用 case _模式来避免
模式可以包含随意定义的条件,称做 守卫
你可以对表达式的类型进行匹配; 优先选择模式匹配而不是 isInstanceOf / asInstanceOf
你可以匹配数组、元组 和 样例类 的模式,然后将匹配到的不同部分绑定到变量
在 for 表达式中, 不能匹配的情况 会被安静的跳过
样式类,是编译器会为之 自动产出 模式匹配 所需要的方法的类
样例类 继承层级中 的 公共超类 应该是 sealed 的
用 Option 来存放对于 maybe exist or not 的 value。 这比 null 更安全
package com.x.p14match
import java.lang.Character
/**
* Date : 2016-04-12
*/
object Matchtest {
def main(args: Array[String]) {
/** 14.1 best switch **/
var sign = -20
var ch: Char = '-'
sign = ch match {
case '+' => 1
case '-' => -1
case _ => 0
}
println("sign : " + sign)
// scala 模式匹配 与 switch 是不同的
// you can use anytype in match. not only number
/** 14.2 守卫 **/
ch = '8'
var digit = 0
ch match {
case '+' => 1
case '-' => -1
case _ if Character.isDigit(ch) => digit = Character.digit(ch, 10) // 0 ~ 9
case _ => sign = 2
}
println("sign : " + sign)
println("digit : " + digit)
/** 14.3 模式中的变量 **/
// match中 变量 必须以小写字母开头, 否则 需要 `varname`
/** 14.4 类型模式 **/
var obj: Any = "123"
var mk = obj match {
case x: Int => x
case s: String => Integer.parseInt(s)
case _: BigInt => Int.MaxValue
case _ => 0
}
println("type_k : " + mk)
/** 14.5 匹配数据, 列表, 元组 **/
// array
val numArr = new Array[Int](5)
numArr(0) = 1
for (i <- 0 until numArr.length)
println(i + ": " + numArr(i))
val na_res = numArr match {
case Array(0) => "0" // inclue 0 array, only one elem, is 0
case Array(x, y) => x + " " + y // only have 2 element array
case Array(0, _*) => "0 ..." // any by 0 begin array
case _ => "something else"
}
println("na_res : " + na_res)
// list
val lst = List(0, 8, 9)
val lstRes = lst match {
case 0 :: Nil => "0"
case x :: y :: Nil => x + " and " + y
case 0 :: tail => "0 ..."
case _ => "something else"
}
println("lstRes : " + lstRes)
// tuple
val pair = (2, 3.14, "Hello")
val pairRes = pair match {
case (0, _, _) => "0 ..."
case (y, z, x) => z + 5
case _ => "neither is 0"
}
println("pairRes : " + pairRes)
/** 14.6 提取器 **/
/** 14.7 变量声明中的模式 **/
val (x, y) = (1, 2)
println(x + y)
val (q, r) = BigInt(10) /% 3
val Array(first, second, _*) = numArr
println("first : " + first)
/** 14.8 for 表达式中的模式 **/
import scala.collection.JavaConversions.propertiesAsScalaMap // 将 Java 的 Properties 转换成 Scala 映射
for ((k, v) <- System.getProperties() if v == "")
println("key : " + k)
/** 14.9 样例类 **/
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。