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