快学scala之Array、List、tuple模式匹配

时间:2021-03-23 19:48:11
object operate_match {

  def main(args: Array[String]) {

    // map match
    val map = Map("scala" -> "spark", "java" -> "hadoop")
    map match {
      case m: Map[_, _] => println("--------------")
      case _ => println("nothing")
    }

    //arr match
    val arr = Array(0, 2, 3, 4)
    arr match {
      case Array(0) => println(0) //match array which has one element
      case Array(x, y) => println(x + y) //match which has two element
      case Array(0, _*) => println("0......") //match first element is 0
      case _ => println("something ") // default
    }
    //match List
    val list = "apple" :: "pear" :: "mango" :: Nil  list match {
      case "" :: Nil => "sale out"  case x :: y => x + " " + y
      case _ => "no fruit"  }
    //match tuple
    val tuple = ("taobao", "baidu", "QQ", "google")
    tuple match {
      case ("", _, _, _) => "0......"  case (x, _, y, _) => x + " " //元组不支持_*匹配
      case _ => " no such company"  }
    /*
    提取器背后是extractor机制,带有从对象中提取值的unapplyunapplySeq方法
    unapply提取的是一个序列
     */

    //变量中的模式
    val (x, y) = (1, 2) // x = 1 , y = 2
    val (q, r) = BigInt(10) /% 3 // /*表示商和余数的对偶 q: r:余数
    val Array(first, second, _*) = arr // first second 为第一,第二个

    //获取系统配置
    import scala.collection.JavaConversions.propertiesAsScalaMap
    for ((k, v) <- System.getProperties()) println(k + "\t" + v)

    val litchi = Litchi("Litchi", 8.0)
    litchi match {
      //      case Apple(v) => "name : " + v
      case Litchi(n, p) => "name : " + n + "\t price : " + p
//            case Nothing => "no fruit"
    }
  }


  //Option类型:表示可能存在,也可能不存在的类型(要么为空,要么带单个元素)
  //Some("")表示包含某个值
  //Map.get返回Option如果对于给定的键没有对应的值返回None,如果有值返回Some

  //偏函数:PartialFunction[A,B](A是参数类型,B返回类型)
  //有两个方法apply:从匹配的模式计算函数值,isDefineAt对输入匹配一个模式是返回true
  val f: PartialFunction[Char, Int] = {
    case '+' => 1
    case '-' => -1
  }
  f.isDefinedAt('0') // 返回false
  f('+') //返回 1
  //  f('0')  //抛出MatchError

}