What is the forSome keyword in Scala for?

Scala

Scala Problem Overview


I found the following code snippet:

List[T] forSome { type T }

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

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

Scala Solutions


Solution 1 - Scala

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.

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

Also see this blog post which is where I got this example from.

Solution 2 - Scala

I don't know Scala, but your question picked up my interest and started Googling.

I found that in Scala's changelog:

> "It is now possible to define existential types using the new keyword > forSome. An existential type has the form T forSome {Q} where Q is a > sequence of value and/or type declarations. "

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFreewindView Question on Stackoverflow
Solution 1 - ScalaAsumu TakikawaView Answer on Stackoverflow
Solution 2 - ScalaGregory PakoszView Answer on Stackoverflow