Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Circumventing variance checks via the map method

Tags:

scala

Set is invariant in its type parameter, so obviously this won't work:

val set: Set[Any] = Set[Int](1, 2, 3)

But then why does this work?

val set: Set[Any] = Set[Int](1, 2, 3).map(identity)

Can anyone explain it? Thanks

like image 654
Lasf Avatar asked Mar 31 '19 04:03

Lasf


1 Answers

First of all, identity takes a type parameter. In this case, the type parameter to identity is inferred as Any, so what is passed to map is identity[Any] (an Any => Any function). map expects an Int => A for some type A. Since functions are contravariant in their argument types, Any => Any can be passed there. So, what your code does is create a new set by mapping each of the original set's elements to have type Any. The full types can be written out like this:

val set: Set[Any] = Set[Int](1, 2, 3).map[Any, Set[Any]](identity[Any])
like image 189
Brian McCutchon Avatar answered Oct 08 '22 18:10

Brian McCutchon