简体   繁体   中英

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM