關於Scala中的match case方法的使用


在scala中有一個方法 match 類似於java內的 switch,但是其功能卻比 switch 強大了不止一點

switch:條件分支

match:模式匹配

在java內使用switch若是不加break將會導致穿透,但是match卻不需要擔心,其用法類似switch,常配合case使用

//值的匹配

val a = 3
val x = a match{
    case 3 => "1"
    case 4 => "2"
    case 5 => "3"
    case _ => "default"      
}
println(x) // 1

//這里值不限定於數值類型,其他類型同樣適用
val b = "1"
val y = b match {
    case "1" => "剪刀"
    case "2" => "石頭"
    case "3" => ""
}
println(y) // "剪刀"

//多值的匹配

List(5,10,15,20) match{
    case one :: two :: three => println(one,three) // :: 為中綴表達式
    case _ => println("hehe")  // _通配符 在這作用相當於switch內結尾的default
}
// (5,List(15,20))

 //模式守衛

val a = 3
val b = a match {
  case a if (a>0)  => "值大於0"
  case _ => "值小於0"  
}
println(b)  //值大於0

 

var a = List(1,2,3,4)
var b = a.groupBy(x=>x match{
     case x if (x%2==0)  => "even number"
     case _ => "uneven number"
})
println(b)  //Map(even number -> List(2, 4), uneven number -> List(1, 3))

 //類型轉換

def a(x:Any)={
    x match{
        case i:Int => x.asInstanceOf[Int] + 10
        case i:String => "hello"
        case _ => x
    }
}
print(a(20))  //30

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM