scala编译器应该为我在下面评论过的if语句生成警告,但它不会。为什么?为什么scala编译器在模式匹配中总是产生false的if语句不会生成警告?
sealed trait T
object A extends T
val s:Seq[T] = Seq(A)
val result = s.map {
//This if should produce a compiler warning
case a if(a == "A") =>
"First"
case a =>
//This if should produce a compiler warning
if (a == "A") {
"Second"
}
else
{
"Third"
}
}
其结果将是“第三条:”如你所期望,但是编译器应该产生在case a if(a == "A")
并在if (a == "A")
警告,但可惜没有警告。
如果我写了下面的代码,它的行为像我期望:
if(A == "A"){
println("can't happen")
}
// warning: comparing values of types A.type and String using `==' will always yield false
这究竟是为什么?
编辑:我正在使用Scala 2.10.1。
我相信,当你使用模式匹配,你需要指定每个个案的类型,否则你会匹配任何内容。尝试将其改为“case a:A if(a ==”A“)=> ...”。 – Felix 2013-04-23 18:46:37
我试过用case a:T if(a ==“A”)=>'仍然没有警告。 – coltfred 2013-04-23 18:48:56