原创转载请注明出处:http://agilestyle.iteye.com/blog/2333026
基于值的模式匹配
A match expression compares a value against a selection of possibilities. All match expressions begin with the value you want to compare, followed by the keyword match, an opening curly brace, and then a set of possible matches and their associated actions, and ends with a closing curly brace. Each possible match and its associated action begins with the keyword case followed by an expression. The expression is evaluated and compared to the target value. If it matches, the expression to the right of the => (“rocket”) produces the result of the match expression.
package org.fool.scala.basic object ScalaMatchExpressions extends App { def matchColor(color: String): String = { color match { case "red" => "RED" case "blue" => "BLUE" case "green" => "GREEN" case _ => "UNKNOWN COLOR: " + color } } println(matchColor("red")) println(matchColor("white")) }
Console Output
基于类型的模式匹配
参数类型Any允许任何类型的参数。如果向某个方法传递的类型具有多样性,并且他们没有任何共性成分,那么Any就可以解决此问题。下划线的作用是通配符,用来匹配任何与前面的值不匹配的对象。
package org.fool.scala.basic case class Person(name: String) object ScalaPatternMatchingWithTypes extends App { def acceptAnything(x: Any): String = { x match { case s: String => "A String: " + s case i: Int if (i < 20) => s"An Int Less than 20: $i" case i: Int => s"Some Other Int: $i" case p: Person => s"A person ${p.name}" case _ => "I have no fucking idea!" } } println(acceptAnything(5)) println(acceptAnything(25)) println(acceptAnything("Hello World")) val p = Person("Kobe") println(acceptAnything(p)) println(acceptAnything(Vector(1, 2, 3))) }
Console Output
基于case类的模式匹配
package org.fool.scala.basic case class Passenger(first: String, last: String) case class Train(travelers: Vector[Passenger], line: String) case class Bus(passengers: Vector[Passenger], capacity: Int) object PatternMatchingCaseClasses extends App { def travel(transport: Any): String = { transport match { case Train(travelers, line) => s"Train line $line $travelers" case Bus(travelers, seats) => s"Bus size $seats $travelers" case Passenger => "Walking along" case what => s"$what is in limbo!" } } val travellers = Vector( Passenger("Kobe", "Bryant"), Passenger("Michael", "Jordan") ) val trip = Vector( Train(travellers, "CRH Train"), Bus(travellers, 100) ) println(travel(trip(0))) println(travel(trip(1))) }
Note:
没有任何类型的标识符(what),表示它会匹配上面各个case表达式未匹配的任何其他事物。
Console Output