why is it that something like:
val map = Map(....)
List(1,2,3,4).contains(map)
or
List(1,2,3,4).contains("hello")
Are allowed to compile. I though scala was type safe.
why is it that something like:
val map = Map(....)
List(1,2,3,4).contains(map)
or
List(1,2,3,4).contains("hello")
Are allowed to compile. I though scala was type safe.
If we consult the scaladocs for List.contains, you will notice the following method signature:
def contains[A1 >: A](elem: A1): Boolean
Of particular interest is the type parameters, [A1 >: A]
If we break this down, we get:
A
, the type of the elements that the List containsA1
, the type of the element you are searching for in the List>:
, a symbol representing a lower boundThis should be interpreted that A1 is lower bounded by A, so A1 is either of type A or a more generic type. See http://www.scala-lang.org/old/node/137 for more information about lower type bounds.
You have a list of Int
. You ask if the list contains a String
. Since Any >: String
and Any >: Int
, the compiler doesn't complain. The same circumstances apply for the Map
scenario.