col*_*red 6 scala scala-compiler
scala编译器应该为我在下面评论过的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"
}
}
Run Code Online (Sandbox Code Playgroud)
其结果将是"第三条:"如你所期望,但是编译器应该产生一个警告就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
Run Code Online (Sandbox Code Playgroud)
为什么会这样?
编辑:我正在使用Scala 2.10.1.
因为它有可能发生。如果我只是保留一些内部状态并在第一次和第二次调用时返回 ==“A” 的不同结果,那么我可以获得“Second”。
您提供了 A 的定义,保证它不会发生,但这需要检查整个程序,并且编译器警告仅是本地的。
| 归档时间: |
|
| 查看次数: |
180 次 |
| 最近记录: |