scala 模式匹配

https://blog.csdn.net/bluishglc/article/details/50995939


scala> val a = Array(1,2,3,4) a: Array[Int] = Array(1, 2, 3, 4)

匿名函数,由繁入简,

 使用case语句构造匿名函数的“额外”好处,

 case语句(组合)除了可以被编译为匿名函数(类型是FunctionX,在Scala里,所有的函数字面量都是一个对象,这个对象的类型是FunctionX),还可以非常方便的编译为一个偏函数PartialFunction!(注意:PartialFunction同时是Function1的子类)编译器会根据调用处的函数类型声明自动帮我们判定如何编译这个case语句(组合)

 case语句声明的变量就是偏函数的参数,既然case语句只能声明一个变量,那么偏函数受限于此,也只能有一个参数!


scala> a.map(x => x match {
     |   case 0 => "zero"
     |   case 1 => "one"
     |   case 2 => "two"
     |   case _ => "other"
     | })
res2: Array[String] = Array(one, two, other, other)


scala> a.map(x => x match { case x => x })
res4: Array[Int] = Array(1, 2, 3, 4)



scala> a.map(case x => x)
<console>:1: error: illegal start of simple expression
a.map(case x => x)
      ^


scala> a.map{case x => x}
res3: Array[Int] = Array(1, 2, 3, 4)


scala> a.map{x => x}
res7: Array[Int] = Array(1, 2, 3, 4)
原文地址:https://www.cnblogs.com/TMatrix52/p/12080594.html