欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

scala match匹配

程序员文章站 2022-06-14 17:14:55
...

match 常用类型匹配

object TestMatch {
    def main(args: Array[String]): Unit = {
        matchAny("a")
        matchArray()
        matchTuple()
        caseClassMacth()
        matchEnum()

    }


    def matchAny(x:Any): Unit ={

        // 用  match   来替代 isInstanceOf   和  asInstanceOf
/*
        if(ch.isInstanceOf[Char]){
            val c = ch.asInstanceOf[Char]
        }*/

        val result = x match{
            case x:String => "space"
            case x:Char =>  x
            case _ => 0
        }
        println(result)
    }

    // 匹配数组
    def matchArray(): Unit ={
        val arr = Array[Int](0,5,1)
        arr match {
            case Array(x,y) => println(s"x=$x \t y=$y")
            case Array(0,_*) => println("0,_*")
            case _ => println("error")
        }
    }

    // 匹配  元组

    def matchTuple(): Unit ={
        val tuple = new Tuple2("aa","bb")
        println(tuple._1)

        // 常用 下面这种方式
        val (spring,summer,autumn,winter) = ("a","b","c","d")
        println(spring)
    }


    //  caseClass
    def caseClassMacth(): Unit ={
        abstract class Expr
        case class Var(name:String) extends Expr
        case class Number(num:Double) extends Expr
        case class UnOp(operator : String , arg : Expr) extends Expr
        case class BinOp(operator : String , left : Expr , right : Expr) extends Expr
        def simplifyTop(expr : Expr) : Expr = expr match{
            case UnOp("-" , UnOp("-" , e)) => e
            case BinOp("+" , e , Number(0)) => e
            case BinOp("*" , e , Number(1)) => e
            case _ => expr
        }
        println(simplifyTop(BinOp("+",Number(num = 2),Number(num = 0))))
    }

    //模拟枚举  enum
    def matchEnum(): Unit ={
        //sealed 结合  case class 方式 定义枚举     sealed密封 关键字修饰
        sealed abstract class TrafficLight  // 父类
        // red yellow  green  子类
        case class RED(stop:String) extends TrafficLight
        case class YELLOW(warning:String) extends TrafficLight
        case class GREEN(go:String) extends TrafficLight

        val light:TrafficLight= RED(" stop")
        light match {
            case RED(stop) => println(stop)
            case YELLOW(stop) => println(YELLOW)
            case GREEN(stop) => println(GREEN)
        }



        //extends Enumeration 方式 定义枚举

         class Season extends Enumeration{
             val SPRITNG,SUMMER,AUtUMN,WINTER = Value  // 大写   不是values
         }
        val season = new Season
        println(season.SPRITNG)
    }


}