Scala进阶源码实战之四——模式匹配

basic

package PatternMatch

object patternmatch {
  println("Welcome to the Scala worksheet")       //> Welcome to the Scala worksheet

      val data =2                                 //> data  : Int = 2
    data match {
        case 1 => println("First")
        case 2 => println("Second")
        case _ => println("Not Known Number")
      }                                       //> Second

    val result = data match {
      case i if i == 1 => "The First"
      case number if number ==2 => "The Second" + number
      case _ => "Not Known Number"
      }                                       //> result  : String = The Second2
    println(result)                               //> The Second2

    "Spark !" foreach { c => println (
        c match {
          case ' ' => "space"
          case ch => "Char: " + ch
        }
        )}                                    //> Char: S
                                                  //| Char: p
                                                  //| Char: a
                                                  //| Char: r
                                                  //| Char: k
                                                  //| space
                                                  //| Char: !

    //匹配类型                                          
    def match_type(t : Any) = t match {
    case p : Int => println("It is Integer")
    case p : String => println("It is String, the content is : " + p)
    case m: Map[_, _] => m.foreach(println)
    case _ => println("Unknown type!!!")
    }                                             //> match_type: (t: Any)Unit

    match_type(2)                                 //> It is Integer
    match_type("Spark")                           //> It is String, the content is : Spark
    match_type(Map("Scala" -> "Spark"))           //> (Scala,Spark)

    def match_array(arr : Any) = arr match {
      case Array(0) => println("Array:" + "0")
      case Array(x, y) => println("Array:" + x + " " +y)
      case Array(0, _*) => println("Array:" + "0 ...")  //*代表多个
      case _ => println("something else")
    }                                         //> match_array: (arr: Any)Unit

    match_array(Array(0))                         //> Array:0
    match_array(Array(0,1))                       //> Array:0 1
    match_array(Array(0,1,2,3,4,5))               //> Array:0 ...


    def match_list(lst : Any) = lst match {
      case 0 :: Nil => println("List:" + "0")          //nil 代表开头
      case x :: y :: Nil => println("List:" + x + " " + y)
      case 0 :: tail => println("List:" + "0 ...")
      case _ => println("something else")
    }                                         //> match_list: (lst: Any)Unit

    match_list(List(0))                           //> List:0
    match_list(List(3,4))                         //> List:3 4
    match_list(List(0,1,2,3,4,5))                 //> List:0 ...


    def match_tuple(tuple : Any) = tuple match {
    case (0, _) => println("Tuple:" + "0")
    case (x, 0) => println("Tuple:" + x )
    case _ => println("something else")
    }                                             //> match_tuple: (tuple: Any)Unit

    match_tuple((0,"Scala"))                      //> Tuple:0
    match_tuple((2,0))                            //> Tuple:2
    match_tuple((0,1,2,3,4,5))                    //> something else
}

提取器

package PatternMatch

object extrator {
  println("Welcome to the Scala worksheet")       //> Welcome to the Scala worksheet

  def match_array(arr : Any) = arr match {
      case Array(0) => println("Array:" + "0")
      case Array(x, y) => println("Array:" + x + " " +y)
      case Array(0, _*) => println("Array:" + "0 ...")
      case _ => println("something else")
    }                                         //> match_array: (arr: Any)Unit

    match_array(Array(0))                         //> Array:0
    match_array(Array(0,1))                       //> Array:0 1
    match_array(Array(0,1,2,3,4,5))               //> Array:0 ...

    val pattern = "([0-9]+) ([a-z]+)".r           //> pattern  : scala.util.matching.Regex = ([0-9]+) ([a-z]+)
        "20150628 hadoop" match {
          case pattern(num, item) => println(num + " : " + item)
        }                                 //> 20150628 : hadoop



}

case class

package PatternMatch




object casecalss {
  println("Welcome to the Scala worksheet")       //> Welcome to the Scala worksheet


 abstract class Person
 case class Student(age: Int) extends Person
 case class Worker(age: Int, salary: Double) extends Person
 case object Shared extends Person

  def caseOps(person: Person) =  person match {
          case Student(age) => println("I am " + age + "years old")
          case Worker(_, salary) => println("Wow, I got " + salary)
          case Shared => println("No property")
          }                               //> caseOps: (person: PatternMatch.casecalss.Person)Unit
      caseOps(Student(19))                    //> I am 19years old
      caseOps(Shared)                         //> No property

  val worker = Worker(29, 10000.1)                //> worker  : PatternMatch.casecalss.Worker = Worker(29,10000.1)
  //def copy(age: Int, salary: Double): Worker
    val worker2 = worker.copy(salary = 19.95) //> worker2  : PatternMatch.casecalss.Worker = Worker(29,19.95)
    val worker3 = worker.copy(age = 30)       //> worker3  : PatternMatch.casecalss.Worker = Worker(30,10000.1)


    //Option_Internal
      val scores = Map("Alice" -> 99, "Spark" -> 100)
                                                  //> scores  : scala.collection.immutable.Map[String,Int] = Map(Alice -> 99, Spar
                                                  //| k -> 100)

    scores.get("Spark") match {
      case Some(score) => println(score)
      case None => println("No score")
    }                                         //> 100
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值