Underscore for existential type in Scala

I read a blog about existential type in Scala: Existential types in Scala

In this blog, he mentions an example:

Map[Class[T forSome { type T}], String] Map[Class[T] forSome { type T}, String] Map[Class[T], String] forSome { type T} 

His explanation. "the third is a supertype of all types of cards for which there is some T such that they are Map [Class [T], String]. So, we have some type of fixed type for the keys on the map - it's just this time we don’t we know what it is. The middle one has keys of type Class [T] forSome {type T}. That is, his keys are classes that are allowed to have whatever value they want for their type. So this is what we really wanted to. "

The explanation is not easy to follow. What are the differences between the second and third in the sample code? Can someone give us some examples?

The blog also mentions that Map[Class[_], String] equivalent to the third in the example when we really want the second. Will this affect semantics when we use _ for the existential type?

+6
source share
1 answer

What is the difference between second and third in the sample code?

In the third type, you cannot have two keys of type Class[T] with different T , for example. Map(classOf[Object] -> "Object", classOf[String] -> "String") does not have this type (but it has the second type).

The blog also mentions that Map[Class[_], String] equivalent to the third in the example when we really want the second.

The post mentions that this may be changed in the future, and it is. Now this is equivalent to the second. See This Example in the Scala Specification :

The type List[List[_]] equivalent to the existential type List[List[t] forSome { type t }] .

Will this affect semantics when we use _ for the existential type?

It depends on what you want in your particular case. Use _ if it gives the desired type (according to the specification above), and you consider it more readable than the forSome form; use forSome otherwise.

+5
source

All Articles