What is the forSome keyword in Scala for?

I found the following code snippet:

List[T] forSome { type T } 

forSome looks like a method, but my friend told me this keyword.

I searched for it but found some forSome . What does this mean and where can I get some documents about it?

+63
scala
Feb 25 2018-12-25T00:
source share
2 answers

The forSome used to define existential types in Scala. This Scala glossary page explains what it is. I could not 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 the exact definition of existential types in the Scala specification , but it's pretty tight.

To summarize some of the posts I'm connected with, existential types are useful when you want to work on something, but don't care about the details of the type in it. For example, you want to work with arrays, but no matter what type of array:

 def printFirst(x : Array[T] forSome {type T}) = println(x(0)) 

which you can also use with a type variable in a method:

 def printFirst[T](x : Array[T]) = println(x(0)) 

but you may not want to add a type variable in some cases. You can also add a binding to a type variable:

 def addToFirst(x : Array[T] forSome {type T <: Integer}) = x(0) + 1 

Also see this blog post in which I got this example.

+43
Feb 25 2018-12-25T00:
source share

I do not know Scala, but your question raised my interest and started Googling.

I found that in Scala changelog :

"Now you can define the types of existence using the new forSome keyword. The existential type is T forSome {Q} , where Q are sequences of values ​​and / or types."

+3
Feb 25 2018-12-12T00:
source share



All Articles