快学Scala(14)--模式匹配和样例类

更好的switch

  def main(args: Array[String]): Unit = {
    var sign: Int = 0
    val ch: Char = '+'
    val color = Color.BLACK
    sign = ch match {
      case '+' => 1
      case '-' => -1
      case _ => 0
    }
    color match {
      case Color.RED => ;
      case Color.BLACK => ;
      case _ => ;
    }
    println(sign)
  }

  

守卫

case _ if Charactrt.isDigit(ch) => digit = Character.digit(ch, 10)

模式匹配

obj match {
  case x: Int => x
  case s: String => Integer.parseInt(s)
  case _: BigInt => Int.MaxValue
  case _ => 0
}

  注:匹配发生在运行期,Java虚拟机中泛型的类型信息是被擦掉的。因此,不能用类型来匹配特定的Map类型。但对于数组而言元素的类型是完好的。

匹配数组、列表和元组

  def main(args: Array[String]): Unit = {
    val arr = Array(0)
    var result = arr match {
      case Array(0) => "0"       //匹配一个包含且只包含0的数组
      case Array(x, y) => x+""+y   //匹配任何带有两个元素的数组
      case Array(0, _*) => "0 ..."  //匹配任何以0开头的数组
      case _=> "something else"
    }
    println(result)
  }

  

  def main(args: Array[String]): Unit = {
    val lst = List{1,2,3}
    var result = lst match {
      case 0 :: Nil => "0"
      case x :: y :: Nil => x + "" + y
      case 0 :: tail => "0 ..."
      case _ => "something else"
    }
  }

  

  def main(args: Array[String]): Unit = {
    val pair = Tuple2(0, 2)
    val result = pair match {
      case (0, _) => "0 ..."
      case (y, 0) => y + "0"
      case _ => "neither is 0"
    }
    println(result)
  }

  

中置表示法

amt match { case a Currency u => ...} //等同于case Currency(a, u)

偏函数

  def main(args: Array[String]): Unit = {
    val result = "-3+4".collect {case '-' => -1; case '+' => 1}
    println(result)  //Vector(-1, 1)
  }

  apply方法从匹配到的模式计算函数值,而isDefinedAt方法在输入至少匹配其中一个模式时返回TRUE。

原文地址:https://www.cnblogs.com/PaulingZhou/p/6672440.html