1.常量匹配
輸出結果def constantmatch(x: int): string = x match
def constantmathtest()=
2.列表匹配one
many
輸出結果def sequencematch(x: list[int]): string = x match
def sequencemathtest() =
3.構造器匹配匹配5元素開頭的三元素列表
其他匹配以1開頭任意數目的列表
輸出結果def constructormatch(x: person): string = x match
def constructormatchtest() =
4.元組匹配name
:tom,age
:12name
:tom,age
:49name
:tom,age
:49
輸出結果def tuplematch(x: any): string = x match
def tuplematchtest() =
5.型別匹配匹配二元組,元素為1,2
匹配三元組,元素為1,2,3
執行結果def typematch(x: any): string = x match
def typematchtest() =
字串型別匹配 字串
整形匹配 5
person(tom,25)
執行結果def ifmatch(x: (int, int)): string = x match
def ifmatchtest() =
非法的分數表示
合法的分數表示:3/8
scala模式匹配
這是scala中最有用的部分之一。匹配值val times 1 times match 使用守衛進行匹配 times match 注意我們是怎樣將值賦給變數 i 的。在最後一行指令中的 是乙個萬用字元 它保證了我們可以處理所有的情況。否則當傳進乙個不能被匹配的數字的時候,你將獲得乙個執行時錯誤。我們...
scala模式匹配
這是scala中最有用的部分之一。匹配值val times 1 times match 使用守衛進行匹配 times match 注意我們是怎樣將值賦給變數 i 的。在最後一行指令中的 是乙個萬用字元 它保證了我們可以處理所有的情況。否則當傳進乙個不能被匹配的數字的時候,你將獲得乙個執行時錯誤。我們...
Scala模式匹配
並且scala還提供了樣例類,對模式匹配進行了優化,可以快速進行匹配。1 匹配字串 todo 匹配字串 定義乙個陣列 val arr array hadoop zookeeper spark storm 隨機取陣列中的一位,使用random.nextint val name arr random.n...