Scala 中的 forSome 关键字是做什么用的?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9444958/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the forSome keyword in Scala for?
提问by Freewind
I found the following code snippet:
我找到了以下代码片段:
List[T] forSome { type T }
The forSomelooks 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. 这是什么意思,我从哪里可以获得有关它的一些文件?
采纳答案by Asumu Takikawa
The forSomekeyword is used to define existential types in Scala. There's this Scala glossarypage explaining what they are. I couldn't find a place in the Scala docs explaining them in detail, so hereis a blog article I found on Google explaining how they are useful.
该forSome关键字用于Scala中定义生存类型。有这个 Scala词汇表页面解释了它们是什么。我在 Scala 文档中找不到详细解释它们的地方,所以这是我在 Google 上找到的一篇博客文章,解释了它们的用处。
Update: you can find a precise definition of existential types in the Scala specificationbut it is quite dense.
更新:您可以在Scala 规范中找到存在类型的精确定义,但它非常密集。
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 kindof 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
Also see this blog postwhich is where I got this example from.
另请参阅此博客文章,这是我从中获得此示例的地方。
回答by Gregory Pakosz
I don't know Scala, but your question picked up my interest and started Googling.
我不知道 Scala,但你的问题引起了我的兴趣并开始使用谷歌搜索。
I found that in Scala's changelog:
我在Scala 的更新日志中发现:
"It is now possible to define existential types using the new keyword
forSome. An existential type has the formT forSome {Q}whereQis a sequence of value and/or type declarations. "
“现在可以使用 new 关键字定义存在类型
forSome。存在类型的形式为T forSome {Q}whereQ是值和/或类型声明的序列。“

