The basic functional cornerstones of Scala: immutable data types, passing of functions as parameters and pattern matching.
1. Basic Pattern Matching
  In Scala, your cases can include types, wildcards, sequences, regular expressions, and so forth.

scala> def printNum(int: Int) {
| int match {
| case => println("Zero")
| case => println("One")
| case _ => println("more than one")
| }
| }
printNum: (int: Int)Unit
scala> printNum()
One
scala> printNum()
Zero
scala> printNum()
more than one

  The underscore "_" wildcard matches anything not defined in the cases above it, just like the default keyword in Java. If you try to put a case _ before any other case clauses, the compiler will throw an unreachable code error on the next clause.

scala> def printNum(int : Int) {
| int match {
| case _ => println("more than one")
| case => println("Zero")
| }
| }
<console>:: error: unreachable code
case => println("Zero")
^

  Use the -print option in the Scala compiler to understand the Scala compiler expands a pattern into code.

scalac -print PrintNum.scala
package <empty> {
  final object PrintNum extends java.lang.Object with ScalaObject {
    def printNum(int: Int): Unit = {
    <synthetic> val temp1: Int = int;
      (temp1: Int) match {
      case => {
      scala.this.Predef.println("One")
      }
      case => {
      scala.this.Predef.println("Zero")
      }
      case _ => {
      scala.this.Predef.println("more than one")
      }
      }
    };
    def this(): object PrintNum = {
    PrintNum.super.this();
    ()
  }
  }
}

  The difference of Scala's pattern matching and Java's switch statement.

# Scala
def fibonacci(in: Int):Int = in match {
  case =>
  case =>
  case n => fibonacci(n - ) + fibonacci(n - )
}
# Java
public int fibonacci(int in){
  switch(in){
  case : return ;
  case : return ;
  default: return fibonacci(n - ) + fibonacci(n - );
  }
}

  You can see:

  1) There's no break statement between cases in Scala.
  2) The last case in Scala assigns the default value to the variable n. Pattern matching in Scala is also an expression that returns a value.
  3) In Scala, we can have multiple tests on a single line:

case  | - | - =>
# responds java
case :
case -:
case -:
return ;

  Scala allows guards to be placed in patterns to test for particular conditions that cannot be tested in the pattern declaration itself.

def fib2(in: Int):Int = in match {
case n if n <= 0 =>
case =>
case n => fib2(n-) + fib2(n-)
}

  Guards are very helpful as the amount of logic gets more complex.

2. Matching Any Type
  Example:

scala> val anyList = List(,"A",,2.5,'a')
anyList: List[Any] = List(, A, , 2.5, a)
scala> for(m <- anyList) {
| m match {
| case i: Int => println("Integer: "+i)
| case s: String => println("String: "+s)
| case f: Double => println("Double: "+f)
| case other => println("other: "+other) # 注意other位于其他case之前会导致other之后的case无法访问
| }
| }
Integer:
String: A
Integer:
Double: 2.5
other: a

3. Testing Data Types

  Test an incoming Object to see whether it's a String, an Integer, or something else.

scala> def test2(in: Any) = in match {
| case s: String => "String, length "+s.length
| case i: Int if i > => "Natural Int"
| case i: Int => "Another Int"
| case a: AnyRef => a.getClass.getName
| case _ => "null"
| }
test2: (in: Any)java.lang.String
scala> test2()
res1: java.lang.String = Natural Int
scala> test2("")
res4: java.lang.String = String, length
scala> test2(List())
res5: java.lang.String = scala.collection.immutable.$colon$colon
scala> test2(1.2)
res7: java.lang.String = java.lang.Double
scala> test2(null)
res8: java.lang.String = null
# java code
public String test2(Object in){
    if(in == null)
      return "null";
    if(in instanceof String)
      return "String, length "+(String)in.length();
    if(in instanceof Integer){
      int i = ((Integer)in).intValue();
    if(i>)
      return "Natural Int";
    return "Another Int";
  }
  return in.getClass().getName();
}

4. Pattern Matching in Lists

  In Scala, the cons cell(非空列表) is represented by the '::' case class. '::' is the name of the method and the name of a case class.

scala> val x =
x: Int =
scala> x :: rest
res10: List[Int] = List(, , , )
# note the symmetry(对称性) between creating and matching
scala> (x::rest) match{case Nil => ; case xprime::restprime => println(xprime);println(restprime)} List(, , )

  Then we can extract the head(x) and tail(rest) of the List in pattern matching.

5. Pattern Matching and Lists
  Use pattern matching to sum up all the odd Ints in a List[Int].

scala> def sumOdd(in: List[Int]):Int = in match {
| case Nil =>
| case x::rest if x % == => x + sumOdd(rest)
| case _::rest => sumOdd(rest)
| }
sumOdd: (in: List[Int])Int

  If the list is empty, Nil, then we return 0. The next case extracts the first element from the list and tests to see whether it's odd. If it is, we add it to the sum of the rest of the odd numbers in the list. The default case is to ignore the first element of the list and return the sum of the odd numbers in the rest of the list.

  Replace any number of contiguous identical items with just one instance of that item:

scala> def noPairs[T](in: List[T]): List[T] = in match {
| case Nil => Nil
// the first two elements in the list are the same, so we'll call noPairs with a List that excludes the duplicate element
| case a :: b :: rest if a == b => noPairs(a :: rest)
// return a List of the first element followed by noPairs run on the rest of the List
| case a :: rest => a :: noPairs(rest)
| }
noPairs: [T](in: List[T])List[T]
scala> noPairs(List(,,,))
res32: List[Int] = List(, , )

  Pattern matching can match against constants as well as extract information.

scala> def ignore(in: List[String]): List[String] = in match {
| case Nil => Nil
// if the second element in the List is "ignore" then return the ignore method run on the balance of the List
| case _ :: "ignore" :: rest => ignore(rest)
// return a List created with the first element of the List plus the value of applying the ignore method to the rest of the List
| case x :: rest => x :: ignore(rest)
| }
ignore: (in: List[String])List[String]

  We can also use the class test/cast mechanism to find all the Strings in a List[Any].

scala> def getStrings(in: List[Any]): List[String] = in match {
| case Nil => Nil
| case (s: String) :: rest => s :: getStrings(rest)
| case _ :: rest => getStrings(rest)
| }
getStrings: (in: List[Any])List[String]
scala> getStrings(List(,,"","hello",4.5,'x'))
res11: List[String] = List(, hello)

6. Pattern Matching and Case Classes

  Case classes are classes that get toString, hashCode, and equals methods automatically. It turns out that they also get properties and extractors. Case classes have properties and can be constructed without using the new keyword.

scala> case class Person(name: String, age: Int, valid: Boolean)
defined class Person
scala> val p = Person("David",,true)
p: Person = Person(David,,true)
scala> p.name
res39: String = David
scala> p.hashCode
res41: Int = -

  By default, the properties are read-only, and the case class is immutable.

scala> p.name = "ws"
<console>:: error: reassignment to val
p.name = "ws"
^

  You can also make properties mutable:

scala> case class MPersion(var name: String, var age:Int)
defined class MPersion
scala> val mp = MPersion("ws",)
mp: MPersion = MPersion(ws,)
scala> mp.name
res42: String = ws
scala> mp.name = "ly"
mp.name: String = ly

  How does case class work with pattern matching?

scala> def older(p: Person):Option[String] = p match {
| case Person(name,age,true) if age > => Some(name)
| case _ => None
| }
older: (p: Person)Option[String]

  If valid field is true, the age is extracted and compared against a guard. If the guard succeeds, the person's name is returned, otherwise None is returned.

scala> older(p)
res47: Option[String] = Some(David)
scala> older(Person("Fred",,true))
res49: Option[String] = Some(Fred)
scala> older(Person("Jorge",,true))
res50: Option[String] = None

7. Nested Pattern Matching in Case Classes

  Case classes can contain other case classes, and the pattern matching can be nested, Further, case classes can subclass other case classes.

scala> case class MarriedPerson(override val name: String,
| override val age: Int,
| override val valid: Boolean,
| spouse: Person) extends Person(name,age,valid)
defined class MarriedPerson
scala> val sally = MarriedPerson("Sally",,true,p)
sally: MarriedPerson = Person(Sally,,true)

  Create a method that returns the name of someone who is older or has a spouse who is older:

scala> def mOlder(p: Person): Option[String] = p match{
| case Person(name,age,true) if age > => Some(name)
| case MarriedPerson(name,_,_,Person(_,age,true)) if age > => Some(name)
| case _ => None
| }
mOlder: (p: Person)Option[String]
scala> mOlder(p)
res51: Option[String] = Some(David)
scala> mOlder(sally)
res52: Option[String] = Some(Sally)

8. Pattern Matching As Functions

  You can also pass pattern matching as a parameter to other methods. Scala compiles a pattern match down to a PartialFunction[A,B], which is a subclass of Function1[A,B]. So a pattern can be passed to any method that takes a single parameter function.
  This allow us to reduce this code snippet:

list.filter(a => a match {
  case s: String => true
  case _ => false
})

  into the following snippet:

list.filter(
  case s: String => true
  case _ => false
)

  Patterns are instances. In addition to passing them as parameters, they can also be stored for later use.

  In addition to Function1's apply method, PartialFunction has an isDefinedAt method so that you can test to see whether a pattern matches a given value. If it doesn't match, a MatchError will be raised.

scala> def handleRequest(req: List[String])
| (exceptions: PartialFunction[List[String],String]): String =
| if (exceptions.isDefinedAt(req)) exceptions(req) else
| "Handling URL "+req+" in the normal way"
handleRequest: (req: List[String])(exceptions: PartialFunction[List[String],String])String

  So if the partial function exceptions(the pattern) matches the request req according to the isDefinedAt method, then we allow the request to be handled by the exceptions functon.

scala> def doApi(call: String, params: List[String]): String =
| "Doing API call "+call
scala> handleRequest("foo" :: Nil){
| case "api" :: call :: params => doApi(call,params)}
res54: String = Handling URL List(foo) in the normal way
scala> handleRequest("api"::"foo"::Nil){
| case "api"::call::params=>doApi(call,params)
| }
res57: String = Doing API call foo
scala> val one: PartialFunction[Int,String] = {case  => "one"}
one: PartialFunction[Int,String] = <function1>
scala> one.isDefinedAt()
res58: Boolean = true
scala> one.isDefinedAt()
res59: Boolean = false

  Partial function can be composed into a single function using the orElse method.

scala> val f1: PartialFunction[List[String],String] = {
| case "stuff" :: Nil => "Got some stuff"
| }
f1: PartialFunction[List[String],String] = <function1> scala> val f2: PartialFunction[List[String],String] = {
| case "other" :: params => "Other: "+params
| }
f2: PartialFunction[List[String],String] = <function1> scala> val f3 = f1 orElse f2
f3: PartialFunction[List[String],String] = <function1>

  You can pass them into the handleRequest method:

handleRequest("a"::"b"::Nil)(f3)

  Partial functions replace a lot of the XML configuration files in Java because pattern matching gives you the same declarative facilities as a configuration file.

def dispatch: LiftRules.DispatchPF = {
case Req("api" :: "status" :: Nil, "", GetRequest) => status
case Req("api" :: "messages" :: Nil, "", GetRequest) => getMsgs
case Req("api" :: "messages" :: "long_poll" :: Nil, "", GetRequest) =>
waitForMsgs
case Req("api" :: "messages" :: Nil, "", PostRequest) =>
() => sendMsg(User.currentUser.map(_.id.is), S)
case Req("api" :: "follow" :: Nil, _, GetRequest) =>
following(calcUser)
case Req("api" :: "followers" :: Nil, _, GetRequest) =>
followers(calcUser)
case Req("api" :: "follow" :: Nil, _, PostRequest) =>
performFollow(S.param("user"))
}

Beginning Scala study note(5) Pattern Matching的更多相关文章

  1. Beginning Scala study note(6) Scala Collections

    Scala's object-oriented collections support mutable and immutable type hierarchies. Also support fun ...

  2. Beginning Scala study note(2) Basics of Scala

    1. Variables (1) Three ways to define variables: 1) val refers to define an immutable variable; scal ...

  3. Beginning Scala study note(9) Scala and Java Interoperability

    1. Translating Java Classes to Scala Classes Example 1: # a class declaration in Java public class B ...

  4. Beginning Scala study note(3) Object Orientation in Scala

    1. The three principles of OOP are encapsulation(封装性), inheritance(继承性) and polymorphism(多态性). examp ...

  5. Beginning Scala study note(8) Scala Type System

    1. Unified Type System Scala has a unified type system, enclosed by the type Any at the top of the h ...

  6. Beginning Scala study note(7) Trait

    A trait provides code reusability in Scala by encapsulating method and state and then offing possibi ...

  7. Beginning Scala study note(4) Functional Programming in Scala

    1. Functional programming treats computation as the evaluation of mathematical and avoids state and ...

  8. Beginning Scala study note(1) Geting Started with Scala

    1. Scala is a contraction of "scalable" and "language". It's a fusion of objecte ...

  9. scala pattern matching

    scala语言的一大重要特性之一就是模式匹配.在我看来,这个怎么看都很像java语言中的switch语句,但是,这个仅仅只是像(因为有case关键字),他们毕竟是不同的东西,switch在java中, ...

随机推荐

  1. C数组下标越界

    之前总听说C语言的各种毛病,今天算是遇到一个:数组下标越界 事情经过 两段完成不相干的代码,一段是测温度的,一段是测转速的.两段代码单独运行都没有问题,但是若运行测转速的代码,测温度的数据就会发生错误 ...

  2. G:首页调用“图片视频”的分类和文章(难点)

      1:后台获取:自定义分类的ID (默认分类也可获取)  2:动态获取"自定义分类的ID($cat)"  $cat_title = single_cat_title(' ', f ...

  3. jq 根据值的正负变色

    效果图这样: 意思就是根据最后的百分值变色,值为负变绿色,值为正变红色. 所以只要取到那个标签里的值了,就能根据正负的判断决定颜色. 我的html部分这样: /*不过他们都说我的dom结构不太合理,同 ...

  4. socket 函数

    1.创建套接字并返回一个描述符,该描述符可以用来访问套接字 #include<sys/types.h> #include<sys/socket.h>  int socket(i ...

  5. 如何改变span元素的宽度与高度

    内联元素:也称为行内元素,当多个行内元素连续排列时,他们会显示在一行里面. 内联元素的特性:本身是无法设置宽度和高度属性的,但是可以通过CSS样式来控制,达到我们想要的宽度和高度. span举例1: ...

  6. NOI2016滚粗记

    首先明确,博主是个渣渣... 7月19日 出发啦,准备去哈尔滨,临走时爸爸迟迟不肯离去站台口,凝望着我,心理很感动..内心的压力瞬间增大2333,附候车室图片.. 在火车上怎么也睡不着2333 7月2 ...

  7. javascript 心得

    1.&&和||等逻辑判断运算标记可以当成条件运算来使用例如: var a =  b = c = "12"; (a=="13"&& ...

  8. instanceof运算符

    instanceof运算符:判断该对象是否是某一个类的实例. 语法格式:boolean b = 对象A instanceof 类B://判断A对象是否是B类的实例,如果是返回true. 若对象是类的实 ...

  9. ListView加载性能优化---ViewHolder---分页

    ListView是Android中一个重要的组件,可以使用它加列表数据,用户可以自己定义列表数据,同时ListView的数据加载要借助Adapter,一般情况下要在Adapter类中重写getCoun ...

  10. VS2008控件全部消失

    新建VS2008项目之后,本该位于工具箱的控件全部消失不见,只剩下"#13119"提示,修复方法如下: 注:不一定三步都需要用到,仅在当前步骤无效情况下才用到下一步 1.步骤一 ( ...