Underscore for existential type in Scala

后端 未结 1 352
面向向阳花
面向向阳花 2021-01-02 22:16

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}], S         


        
相关标签:
1条回答
  • 2021-01-02 22:53

    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.

    0 讨论(0)
提交回复
热议问题