Scala 为什么这不会给出一个类型错误?
我希望这会给我一个类型错误,因为Scala 为什么这不会给出一个类型错误?,scala,types,Scala,Types,我希望这会给我一个类型错误,因为中的(String,String),否则案例不是对 case class Pair(x: String, y: String) val value = Console.readLine.toBoolean val Pair(x, y) = if (value) Pair("foo", "bar") else false 相反,如果输入false,则在运行时会出现以下错误 scala.MatchError: (foo,bar) (of class sc
中的(String,String)
,否则
案例不是对
case class Pair(x: String, y: String)
val value = Console.readLine.toBoolean
val Pair(x, y) =
if (value) Pair("foo", "bar")
else false
相反,如果输入false,则在运行时会出现以下错误
scala.MatchError: (foo,bar) (of class scala.Tuple2)
我想解构只是将结果赋给类型为
Any
的变量,然后在其上进行匹配,但不幸的是Scala放任了这一切。如果使用scalac-print
编译此代码,会发生什么。正如您正确地假设的,它只是模式匹配的语法糖。实际上,您的case类扩展了Product,Product也是Tuple2的一个超类,这也是您的代码编译的地方。将您的值分配给Product类型的变量:
val temp6: Product = if (value)
new Main$Pair("foo", "bar")
else
new Tuple2("foo", "bar");
然后对其应用模式匹配:
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)
if(temp6.$isInstanceOf[Main$Pair]())
{
val temp7:Main$Pair=temp6.$asInstanceOf[Main$Pair]();
新的Tuple2(temp7.x(),temp7.y())
}
其他的
抛出新匹配错误(temp6)
但这不应该编译imho。您应该将其发布到scala邮件列表。很高兴知道,但我不认为
产品的常见超类型是它编译的原因。我修改了我的示例来说明这一点,尽管它们都有一个共同的超级类型Any
!