Scala Language Specification specifies syntax of Existential Types as
Type ::= InfixType ExistentialClauses
ExistentialClauses ::= ‘forSome’ ‘{’ ExistentialDcl
{semi ExistentialDcl} ‘}’
ExistentialDcl ::= ‘type’ TypeDcl
| ‘val’ ValDcl
I have seen a lot code use forSome and type together, e.g.
List[T] forSome { type T; }
But I have never seen forSome with val, is there any sample?
If you think about it, you'll soon realize that the only time values appear in types is wit path dependent types. By example:
trait Trait {
val x: { type T }
val y: x.T // path dependent type: here comes our val
}
Applying this to existential types we can now easily cook up a sample of forSome { val:
type SomeList = List[v.T] forSome { val v : { type T }; }
The above type denotes any list whose elements are of a path dependent type v.T.
By example:
object X {
type T = String
val x: T = "hello"
}
val l1: SomeList = List(X.x) // compiles fine
val l2: SomeList = List(123) // does not compile
Granted, SomeList is pretty useless as is. As often, such an existential type would only be really useful as part of a bigger type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With