Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the forSome keyword in Scala for?

Tags:

scala

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?

like image 528
Freewind Avatar asked Feb 25 '12 14:02

Freewind


2 Answers

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.

like image 125
Asumu Takikawa Avatar answered Nov 10 '22 22:11

Asumu Takikawa


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

like image 43
Gregory Pakosz Avatar answered Nov 10 '22 22:11

Gregory Pakosz