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
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With