scala入门 模式匹配

  1. 标准用法
  2. 使用守卫
  3. 类型匹配

标准用法

object MatchExample extends App{
      val count:Int = 1;

      val res = count match {
       case 1 => "one"
       case 2 => "two"
       case 3 => "three"
       case _ => "others"
      }

      println("result is " + res)
}

使用守卫

object MatchExample extends App{
      val count:Int = 1;

      val res = count match {
      case i if i == 1 => "one"
      case i if i == 2 => "two"
      case i if i == 3 => "three"
      case _ => "others"
      }
      println("result is " + res)
}

类型匹配

object MatchExample extends App{
    def chooseObject(obj:Any ) =
        obj match {
          case s: String => println("String")
          case i: Int => println("Int")
          case _ => println("others")
        }

    chooseObject("Linda")
}

Java 中的模式匹配switch只允许匹配byte、short、int、char、String、enum,不允许匹配double、float、long、boolean;

Scala模式匹配的用法更加好用,可以匹配类型(Boolean、Byte、Short、Int、Long、Double、Float、String、Character、)还可以匹配对象;

原文地址:https://www.cnblogs.com/liuyunAlex/p/5113374.html