這里我們轉(zhuǎn)載 Twitter 的 Scala 課堂 ,轉(zhuǎn)載的內(nèi)容基本來自 Twitter 的 Scala 課堂中文翻譯,部分有小改動(dòng).
這是 Scala 中最有用的部分之一。 匹配值
scala> val times = 1
times: Int = 1
scala>
scala> times match {
| case 1 => "one"
| case 2 => "two"
| case _ => "some other number"
| }
res4: String = one
添加條件進(jìn)行匹配
scala> times match {
| case i if i == 1 => "one"
| case i if i == 2 => "two"
| case _ => "some other number"
| }
res5: String = one
注意我們是怎樣將值賦給變量’i’的。
在最后一行指令中的_是一個(gè)通配符;它保證了我們可以處理所有的情況。 否則當(dāng)傳進(jìn)一個(gè)不能被匹配的數(shù)字的時(shí)候,你將獲得一個(gè)運(yùn)行時(shí)錯(cuò)誤。我們以后會(huì)繼續(xù)討論這個(gè)話題的。
你可以使用 match 來分別處理不同類型的值
def bigger(o: Any): Any = {
o match {
case i: Int if i < 0 => i - 1
case i: Int => i + 1
case d: Double if d < 0.0 => d - 0.1
case d: Double => d + 0.1
case text: String => text + "s"
}
}
還記得我們之前的計(jì)算器嗎。 讓我們通過類型對(duì)它們進(jìn)行分類。 一開始會(huì)很痛苦
def calcType(calc: Calculator) = calc match {
case _ if calc.brand == "hp" && calc.model == "20B" => "financial"
case _ if calc.brand == "hp" && calc.model == "48G" => "scientific"
case _ if calc.brand == "hp" && calc.model == "30B" => "business"
case _ => "unknown"
}
(⊙o⊙)哦,太痛苦了。幸好 Scala 提供了一些應(yīng)對(duì)這種情況的有效工具。
使用樣本類可以方便得存儲(chǔ)和匹配類的內(nèi)容。你不用 new 關(guān)鍵字就可以創(chuàng)建它們。
scala> case class Calculator(brand: String, model: String)
defined class Calculator
scala> val hp20b = Calculator("hp", "20b")
hp20b: Calculator = Calculator(hp,20b)
樣本類基于構(gòu)造函數(shù)的參數(shù),自動(dòng)地實(shí)現(xiàn)了相等性和易讀的 toString 方法。
scala> val hp20b = Calculator("hp", "20b")
hp20b: Calculator = Calculator(hp,20b)
scala> val hp20B = Calculator("hp", "20b")
hp20B: Calculator = Calculator(hp,20b)
scala> hp20b == hp20B
res6: Boolean = true
樣本類也可以像普通類那樣擁有方法。 使用樣本類進(jìn)行模式匹配
case classes are designed to be used with pattern matching. Let’s simplify our calculator classifier example from earlier.
樣本類就是被設(shè)計(jì)用在模式匹配中的。讓我們簡化之前的計(jì)算器分類器的例子。
val hp20b = Calculator("hp", "20B")
val hp30b = Calculator("hp", "30B")
def calcType(calc: Calculator) = calc match {
case Calculator("hp", "20B") => "financial"
case Calculator("hp", "48G") => "scientific"
case Calculator("hp", "30B") => "business"
case Calculator(ourBrand, ourModel) => "Calculator: %s %s is of unknown type".format(ourBrand, ourModel)
}
最后一句也可以這樣寫
case Calculator(_, _) => "Calculator of unknown type"
或者我們完全可以不將匹配對(duì)象指定為 Calculator 類型
case _ => "Calculator of unknown type"
或者我們也可以將匹配的值重新命名。
case c@Calculator(_, _) => "Calculator: %s of unknown type".format(c)