Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't the scala compiler generate a warning on if statements that always yield false inside a pattern match?

The scala compiler should generate warnings for the if statements I've commented on below, but it doesn't. Why?

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

The result will be "Third" as you'd expect, but the compiler should have generated a warning on the case a if(a == "A") and on the if (a == "A"), but alas there is no warning.

If I write the following code it behaves like I would expect:

if(A == "A"){
  println("can't happen")
}

// warning: comparing values of types A.type and String using `==' will always yield false

Why is this happening?

Edit: I'm using Scala 2.10.1.

like image 607
coltfred Avatar asked Apr 23 '13 18:04

coltfred


1 Answers

Because it can happen. If I simply kept some internal state and returned different results for == "A" on the first and second call, then I can get "Second".

You've provided a definition of A that guarantees it can't happen, but that requires examination of the whole program, and compiler warnings are only local.

like image 189
Kevin Peterson Avatar answered Sep 23 '22 09:09

Kevin Peterson