Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List(1)#contains() returns `false`

Tags:

scala

Given the following:

scala> List(1).contains()
warning: there was one deprecation warning; re-run with -deprecation for details
res18: Boolean = false

Why does false return?

List#contains has the signature:

def contains[A1 >: A](elem: A1): Boolean

So, as I understand, contains argument must be equal or above A's type.

Why does this return false?

like image 239
Kevin Meredith Avatar asked Jul 04 '26 02:07

Kevin Meredith


1 Answers

If you run it again with -deprecation (as suggested by the warning), you'll see this:

scala> List(1).contains()
<console>:8: warning: Adaptation of argument list by inserting ()
  has been deprecated: this is unlikely to be what you want.
        signature: LinearSeqOptimized.contains[A1 >: A](elem: A1): Boolean
  given arguments: <none>
 after adaptation: LinearSeqOptimized.contains((): Unit)
              List(1).contains()
                              ^
res0: Boolean = false

So List(1).contains() is being parsed as List(1).contains(()), and the inferred type for A1 is AnyVal, which is the least upper bound of Unit and Int.

The short answer: don't do this, it's bad. Slightly longer: don't do this, it's bad, and if the compiler suggests re-running with -deprecation, take it up on the offer—it'll probably make what's going on a little clearer.

like image 54
Travis Brown Avatar answered Jul 06 '26 08:07

Travis Brown