Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Underscore for existential type in Scala

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

In this blog, it 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 one is the supertype of all map types such that there is some T such that they are a Map[Class[T], String]. So again, we've got some fixed class type for keys in the map - it's just that this time we don't know what type it is. The middle one however has keys of type Class[T] forSome { type T }. That is, its keys are classes which are allowed to have any value they want for their type parameter. So this is what we actually wanted."

The explanation is not easy to follow. What are the differences between the second and third one in the code example? Could anyone give us some examples?

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

like image 216
PunyTitan Avatar asked Sep 08 '15 01:09

PunyTitan


1 Answers

What are the differences between the second and third one in the code example?

In the third type you can't have two keys of type Class[T] with different T, e.g. Map(classOf[Object] -> "Object", classOf[String] -> "String") doesn't have this type (but it does have the second type).

The blog also mention that Map[Class[_], String] is equivalent to the third one in the example, when we actually want the second one.

The post mentions this could be changed in the future, and it has. Now it's equivalent to the second one. See this example in Scala Specification:

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

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

It depends on what you want in your specific case. Use _ if it gives the type you want (according to the specification linked above) and you think it's more readable than the forSome form; use forSome otherwise.

like image 131
Alexey Romanov Avatar answered Nov 01 '22 10:11

Alexey Romanov