scala - 模式匹配和樣例類

模式匹配

更好的switch

scala有一個十分強大的模式匹配機制,可以應用在很多場合:switch語句、類型查詢以及“析構”(獲取複雜表達式中的不同部分)。

object Test {
  def main(args: Array[String]): Unit = {
    println(matchTest('-'))
  }

  def matchTest(x:Char):Int = x match {
    case '+' => 1
    case '-' => -1
    case _ => 0
  }
}

1、match對應java裏的switch
2、與switch語句不同。scala模式不會有“意外掉入下一個分支”
3、箭頭符號 => ,隔開模式和表達式
4、如果沒有模式能夠匹配,會拋出MatchError。可以用case_ 模式來避免。
5、與if類似,match是表達式,不是語句

守衛

添加守衛,匹配所有數字。

// Character.digit(ch,radix)返回radix進制的字符ch所表示的十進制數
// 守衛可以是任何Boolean條件
// 模式總是從上往下進行匹配
object Test {
  def main(args: Array[String]): Unit = {
    println(matchTest('-'))
    println(matchTest('2'))
  }

  def matchTest(ch:Char):Int = ch match {
    case '+' => 1
    case '-' => -1
    case _ if Character.isDigit(ch) => Character.digit(ch,10)
    case _ => 0
  }
}

匹配數組、列表和元組

匹配數組
要匹配數組的內容,可以在模式中使用Array表達式。

object Test {
  def main(args: Array[String]): Unit = {
    println(matchTest(Array(0)))
    println(matchTest(Array(0,1)))
    println(matchTest(Array(0,1,2)))
    println(matchTest(Array(1,2,3)))
  }

  def matchTest(arr:Array[Int]):String = arr match {
    case Array(0) => "0"             //匹配只包含0的數組
    case Array(x,y) => x + " " + y   //匹配任何帶有兩個元素的數組,並將這兩個元素分別綁定到變量x和y
    case Array(0,_*) => "0 ..."     //匹配任何以0開始的數組
    case _ => "something else"
  }
}
//輸出結果如下:
0
0 1
0 ...
something else

匹配列表
匹配元組

樣例類

樣例類對模式匹配就行了優化

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章