Kevin Meredith
Kevin Meredith

Reputation: 41939

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

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?

Upvotes: 3

Views: 130

Answers (1)

Travis Brown
Travis Brown

Reputation: 139058

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.

Upvotes: 7

Related Questions