How to prevent contains comparing unrelated types?

Take following code:

object Main {
  def main(args: Array[String]): Unit = {
    val a: String = "answer"
    val i: Int = 42

    val is = Some(i)

    if (i == a) println("Thanks for the fish!")
    if (is.contains(a)) println("Thanks for the fish!")
  }
}

The i == a comparison can be prevented using strictEquality, but how about contains? Its signature final def contains[A1 >: A](elem: A1): Boolean seems equivalent to def contains(elem: Any) in practice.

Is there some way to change the signature in the library so that it requires CanEqual, and we do not have to live with this undetected forever?

And regarding not so distant future, Is there some way to detect this now? IntelliJ Scala plugin had an inspection for this previously, but unfortunately it is not working in Scala 3 (SCL-22295)

-Winfer-union

yields

11 |    if (is.contains(a)) println("Thanks for the fish!")
   |        ^^^^^^^^^^^
   |        A type argument was inferred to be union type Int | String
   |        This may indicate a programming error.

For some reason, it is not reported in REPL.

1 Like