2014年03月03日 星期一 09:23
Scala中的Match表达式类似于C++语言中的switch表达式,但功能比switch更加丰富,写法也更加自然和方便。
Scala's match expression lets you select from a number of alternatives, just like switch statements in other languages. In general a match expression lets you select using arbitrary patterns.
参考示例代码:
object S013_PatternMatch { def simpleMatch(s : Any){ s match { case 200 => println("This is two hundreds.") case "laomeng" => println("Hello, laomeng.") case x: String => println(s"got a string $x") case x: Int => println(s"got a integer $x") case x: Array[Int] => { println(s"got a Int Array:") for(i <- x){ println(i) } } case _ => println("got something else") } } def main(args: Array[String]): Unit = { simpleMatch(100) simpleMatch("mengguang") simpleMatch(Array[Int](1,2,3)) simpleMatch(List[Int](2,3,4)) simpleMatch(200) simpleMatch("laomeng") } }
参考资料:
http://www.artima.com/pins1ed/builtin-control-structures.html#7.5
http://www.artima.com/pins1ed/case-classes-and-pattern-matching.html
Zeuux © 2024
京ICP备05028076号