`forSome {val`的样本?

Fre*_*ind 18 scala

我在scala参考文档中看到,第26页:

3.2.10 Existential Types

    Syntax:

        Type ::= InfixType ExistentialClauses
        ExistentialClauses ::= ‘forSome’ ‘{’ ExistentialDcl
                               {semi ExistentialDcl} ‘}’
        ExistentialDcl ::=   ‘type’ TypeDcl
                           | ‘val’ ValDcl
Run Code Online (Sandbox Code Playgroud)

我已经看到了很多代码使用forSometype在一起,如

List[T] forSome { type T; }
Run Code Online (Sandbox Code Playgroud)

但我从来没有见过forSomeval,有没有样品?

Rég*_*les 16

如果你考虑一下,你很快就会意识到值在类型中出现的唯一时间是机智路径依赖类型.举例:

trait Trait {
  val x: { type T }
  val y: x.T // path dependent type: here comes our val
}
Run Code Online (Sandbox Code Playgroud)

将此应用于存在类型,我们现在可以轻松地制作以下样本forSome { val:

type SomeList = List[v.T] forSome { val v : { type T }; }
Run Code Online (Sandbox Code Playgroud)

上述类型表示其元素具有路径依赖类型的任何列表v.T.

举例:

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
Run Code Online (Sandbox Code Playgroud)

当然,这SomeList是无用的.通常,这种存在类型只会作为更大类型的一部分真正有用.