Why doesn't the scala compiler generate a warning if instructions that always give false inside a pattern match?

The scala compiler should generate warnings for if statements, which I commented below, but this is not the case. 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 would expect, but the compiler should have generated a warning on case a if(a == "A") and on if (a == "A") , but, alas, there is no warning.

If I write the following code, it will behave as 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 am using scala 2.10.1.

+6
source share
2 answers

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

You have provided a definition of A that ensures that this cannot happen, but this requires checking the entire program, and compiler warnings are only local.

+1
source

You might have an inherited class with an overloaded == method with a string argument ...

0
source

Source: https://habr.com/ru/post/943470/


All Articles