scala 基础十三 scala 模式匹配 Match case 的使用


1.scala中的match语句用来在一个列表中选择某一个分支来执行分支的语句块,类似于其他语言中的swtich..case语句

package smart.iot

class matchCase {

}

object matchCase {

  def main(args: Array[String]): Unit = {
    val a: Int = 2;

    a match {
      case 1 => println("A")
      case 2 => println("B")
      case _ => println("oaher")
    }
  }
}

result:
B

 2.match case 中的控制语句

  a match{
    
      case x if x==1 =>println("A")
      case x if x==2 =>println("B")
      case _ =>println("other")
    }
resout:
B

 3.match 类型判断

package smart.iot

class matchCase {

}

object matchCase {

  //定义一个类型判断函数
  def t(obj:Any)= obj match
  {
    case obj:String=>println("type is String")
    case obj:Int=>println("tpye is Int")
    case _=>println("tpye is other")
  }
  
  def main(args: Array[String]): Unit = {

    
    t("hello")
    t(5)
    
 
}
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM