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

2

6

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.

Fenny answered 23/4, 2013 at 18:10 Comment(2)
I believe that when you use pattern matching, you need to specify the type for each case, otherwise you will match anything. Try to change it to "case a:A if (a == "A") =>...".Ulrikaumeko
I tried it with case a:T if(a == "A") => and still no warning.Fenny
S
1

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.

Syl answered 23/4, 2013 at 19:26 Comment(1)
I'm not sure I understand your answer. If I write the expression if (A == "a"){} anywhere in my code I get the compiler warning, but you're saying that somehow the pattern match makes the locality of the declaration matter? Please clarify.Fenny
I
0

May you will have inherited class with overloaded == method with string argument…

Indignant answered 30/4, 2013 at 23:42 Comment(2)
That's true, but the compiler knows that information. I discussed this with Josh Suereth who works at typesafe and his answer was the following "The compiler not generating a warning isn't a bug, but we do wish that warning was more robust." So while it's not a "bug" it isn't implemented.Fenny
So, I hope we will be able to see this warning in future Scala compiler releases :)Lorrianelorrie

© 2022 - 2024 — McMap. All rights reserved.