在下面的第一个代码片段中,case语句在函数内定义,它按预期工作.
def echoWhatYouGaveMe(x: Any): String = x match {
case (a, b) => s"got $a and $b"
case (a, b, c) => s"got $a, $b, and $c"
case _ => "Unknown"
}
object MatchTest extends App {
// trigger the tuple patterns
println(echoWhatYouGaveMe((1,2))) // two element tuple
println(echoWhatYouGaveMe((1,2,3))) // three element tuple
}
MatchTest.main(Array("dummy"))
Run Code Online (Sandbox Code Playgroud)
有1和2
得到1分,2分和3分
下面的情况不在函数内,但在上面非常类似.它给出了一个错误.我理解错误,但我不明白为什么我在下面收到错误而不是上面的错误.
val myTuple = (1, 2, 3)
val toPrint = myTuple match {
case (a, b, c) => s"got $a, $b, …Run Code Online (Sandbox Code Playgroud)