What is the forSome keyword in Scala for?
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?
Solution 1:
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:
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 formT forSome {Q}
whereQ
is a sequence of value and/or type declarations. "