Scala中存在类型的下划线 [英] Underscore for existential type in Scala

查看:176
本文介绍了Scala中存在类型的下划线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在Scala中阅读了有关存在类型的博客:存在类型在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}

他的解释. 第三个是所有地图类型的超类型,因此有一些T表示它们是Map [Class [T],String].因此,再次,我们为地图中的键设置了一些固定的类类型-只是这次我们不知道它是什么类型,但是中间的是类型为[[T] 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?

该博客还提到了Map[Class[_], String]等同于示例中的第三个,而实际上我们需要第二个.当我们将_用于存在类型时,这会影响语义吗?

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?

推荐答案

在代码示例中,第二个和第三个之间有什么区别?

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

在第三种类型中,您不能拥有两个Class[T]类型的键,而这些键具有不同的T,例如Map(classOf[Object] -> "Object", classOf[String] -> "String")没有这种类型(但是确实有第二种类型).

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).

该博客还提到,当我们实际上想要第二个时,Map[Class[_], String]等同于示例中的第三个.

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

该帖子提到将来可能会更改,现在已经更改.现在相当于第二个.请参见 Scala规范:

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:

类型List[List[_]]等同于现有的类型List[List[t] forSome { type t }].

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?

这取决于您在特定情况下想要的东西.如果它提供所需的类型(根据上面的链接说明),请使用_,并且您认为它比forSome格式更具可读性;否则使用forSome.

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.

这篇关于Scala中存在类型的下划线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆