What is the forSome keyword in Scala for?

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.

Leave a Comment