6

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"
      }
}

如您所料,结果将是“第三”,但编译器应该在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。

4

2 回答 2

1

因为它可能发生。如果我只是保留一些内部状态并在第一次和第二次调用时为 == "A" 返回不同的结果,那么我可以得到 "Second"。

您提供了 A 的定义,保证它不会发生,但这需要检查整个程序,并且编译器警告只是局部的。

于 2013-04-23T19:26:10.850 回答
0

愿你继承类的重载==方法和字符串参数...</p>

于 2013-04-30T23:42:36.173 回答