Freewind
Freewind

Reputation: 198238

Sample of `forSome { val `?

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?

Upvotes: 19

Views: 446

Answers (1)

Régis Jean-Gilles
Régis Jean-Gilles

Reputation: 32719

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.

Upvotes: 17

Related Questions