zoukankan      html  css  js  c++  java
  • 快学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。

  • 相关阅读:
    [POI2014]KUR-Couriers
    [题解向] Luogu4092 [HEOI2016/TJOI2016]树
    [探究] OI中各种初级数论算法相关
    [SCOI2005]骑士精神
    [intoj#7]最短距离
    数列分块入门
    动态规划问题基础
    Luogu P1967 货车运输
    Luogu P3379 【模板】最近公共祖先(LCA)
    Luogu P3378 【模板】堆
  • 原文地址:https://www.cnblogs.com/PaulingZhou/p/6672440.html
Copyright © 2011-2022 走看看