Scala 中的 forSome 关键字是做什么用的? [英] What is the forSome keyword in Scala for?

查看:40
本文介绍了Scala 中的 forSome 关键字是做什么用的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了以下代码片段:

I found the following code snippet:

List[T] forSome { type T }

forSome 看起来像一个方法,但我朋友告诉我它是一个关键字.

The forSome looks like a method, but my friend told me it's a keyword.

我用谷歌搜索,但发现关于forSome的文档很少.这是什么意思,我可以从哪里获得有关它的文件?

I googled it, but found few documents about forSome. What does it mean, and where can I get some documents about it?

推荐答案

forSome 关键字用于在 Scala 中定义存在类型.有这个 Scala glossary 页面解释了它们是什么.我在 Scala 文档中找不到详细解释它们的地方,所以 这里 是我在 Google 上找到的一篇博客文章,解释了它们的用途.

The forSome keyword is used to define existential types in Scala. There's this Scala glossary page explaining what they are. I couldn't find a place in the Scala docs explaining them in detail, so here is a blog article I found on Google explaining how they are useful.

更新:您可以在 Scala 规范,但它非常密集.

Update: you can find a precise definition of existential types in the Scala specification but it is quite dense.

总结一下我链接到的一些帖子,当您想对某些内容进行操作但不关心其中类型的详细信息时,存在类型很有用.例如,您想对数组进行操作,但不关心什么样的数组:

To summarize some of the posts I linked to, existential types are useful when you want to operate on something but don't care about the details of the type in it. For example, you want to operate on arrays but don't care what kind of array:

def printFirst(x : Array[T] forSome {type T}) = println(x(0)) 

你也可以用方法上的类型变量来做:

which you could also do with a type variable on the method:

def printFirst[T](x : Array[T]) = println(x(0))

但在某些情况下您可能不想添加类型变量.您还可以为类型变量添加一个绑定:

but you may not want to add the type variable in some cases. You can also add a bound to the type variable:

def addToFirst(x : Array[T] forSome {type T <: Integer}) = x(0) + 1

另见这篇博文得到这个例子.

这篇关于Scala 中的 forSome 关键字是做什么用的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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