问题有点难以表达,所以我将尝试提供一个例子:
def myThing(): (String, String, String) = ("", "", "")
// Illegal, this is a Match
val (`r-1`, `r-2`, `r-3`) = myThing()
// Legal
val `r-1` = myThing()._1
第一个评估是无效的,因为这在技术上是匹配表达式,并且在匹配反引号中标记的标识符被假定为对范围中现有val的引用。
虽然在比赛之外,我可以自由地定义“r-1”。
有没有办法使用复杂的变量名称进行匹配提取?
您可以明确地写出完整的变量名称:
def myThing(): (String, String, String) = ("a", "b", "c")
// legal, syntactic backtick-sugar replaced by explicit variable names
val (r$minus1, r$minus2, r$minus3) = myThing()
println(`r-1`, `r-2`, `r-3`)
但由于可以自由选择变量名称(与Java API中称为yield
等的方法不同),我建议发明更简单的变量名称,r$minusx
-things真的看起来不漂亮。