Scala系列学习四 模式匹配

1、模式匹配

可几乎可以匹配所有的的

object MatchCaseDemo extends App {
  private val p = new MatchCaseDemoClass
  private val arr = Array(1, "allen", p, 2, Array(1, 3, 5, 7), 3.5, 5, 6, 78, List(3, -1), (78, 79, 80))
  println(arr.toBuffer)
  for (a <- arr) {
    a match {
      case "allen" => println("it is allen")
      case x: Int if (x >= 3) => println("The number is" + x)
      case y: MatchCaseDemoClass => println("it is MatchCaseDemoClass")
      case Array(x1, x2, x3, x4) => println(x2)
      case Array(0) => println("only 0")
      case 0 :: Nil => println("only 0")
      case x :: y :: Nil => println(s"x: $x y: $y")
      case 0 :: tail => println("0...")
      case _ => println("other")
    }
  }

}

class MatchCaseDemoClass {
  var name: String = "allen"
}


/*
ArrayBuffer(1, allen, cn.huawei.scala.MatchCaseDemoClass@2d3fcdbd, 2, [I@617c74e5, 3.5, 5, 6, 78, List(3, -1), (78,79,80))
other
it is allen
it is MatchCaseDemoClass
other
3
other
The number is5
The number is6
The number is78
x: 3 y: -1
other
*/

2、利用Option来查看是否可以获取到值

object OptionDemo extends App {
  private val map1 = Map("allen" -> 20, "tom" -> 18)
  val age1 = map1.get("allen") match {
    case Some(i) => i //Some表示包含了某个值
    case None => 0 //表示没有包含某个值
  }
  println(age1)
}

3、偏函数

被包在花括号内没有match的一组case语句是一个偏函数,它是PartialFunction[A, B]的一个实例,A代表参数类型,B代表返回类型,常用作输入模式匹配


object OptionDemo extends App {
  private val map1 = Map("allen" -> 20, "tom" -> 18)
  val age1 = map1.get("allen") match {
    case Some(i) => i //Some表示包含了某个值
    case None => 0 //表示没有包含某个值
  }
  println(age1)

  def f1: PartialFunction[String, Int] = {
    case "allen" => 23
    case "tom" => 20
    case _ => 18
  }

  def f2(name: String): Int = name match {
    case "allen" => 23
    case "tom" => 20
    case _ => 18
  }

  println(f1("allen"))//调用apply方法,从匹配到的模式计算函数值
  println(f1.isDefinedAt("tom"))//调用isDefinedAt方法在输入至少匹配一个模式是返回true
  println(f2("allen"))
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章