我希望这会给我一个类型错误,因为(String, String)在这种else情况下不是Pair.
case class Pair(x: String, y: String)
val value = Console.readLine.toBoolean
val Pair(x, y) =
if (value) Pair("foo", "bar")
else false
Run Code Online (Sandbox Code Playgroud)
相反,如果我输入false,我在运行时会收到以下错误.
scala.MatchError: (foo,bar) (of class scala.Tuple2)
Run Code Online (Sandbox Code Playgroud)
我认为解构只是用于将结果分配给类型变量Any然后匹配的糖,但是Scala让它飞起来似乎很不幸.
如果您编译此代码,scalac -print您会看到会发生什么.正如你想象的那样,它只是模式匹配的语法糖.实际上你的case类扩展了Product,它也是Tuple2的超类,也就是你的代码编译的类.您的值被分配给Product类型的变量:
val temp6: Product = if (value)
new Main$Pair("foo", "bar")
else
new Tuple2("foo", "bar");
Run Code Online (Sandbox Code Playgroud)
然后应用模式匹配:
if (temp6.$isInstanceOf[Main$Pair]())
{
<synthetic> val temp7: Main$Pair = temp6.$asInstanceOf[Main$Pair]();
new Tuple2(temp7.x(), temp7.y())
}
else
throw new MatchError(temp6)
Run Code Online (Sandbox Code Playgroud)
但是,这不应该编译imho.您应该将此发布到scala邮件列表.