公开来自单例类型的路径依赖类型

bet*_*ess 5 scala type-parameter path-dependent-type dependent-method-type

我正在尝试让Scala为来自单例类型的路径依赖类型找到正确的类型.

首先,这是示例的类型容器,以及一个实例:

trait Container {
  type X
  def get(): X
}

val container = new Container {
  type X = String
  def get(): X = ""
}
Run Code Online (Sandbox Code Playgroud)

我可以在第一次尝试中看到String(所以我已经有了一个工作场景):

class WithTypeParam[C <: Container](val c: C) {
  def getFromContainer(): c.X = c.get()
}

val withTypeParam = new WithTypeParam[container.type](container)

// good, I see the String!
val foo: String = withTypeParam.getFromContainer()
Run Code Online (Sandbox Code Playgroud)

但是当没有类型参数时,这不再起作用.

class NoTypeParam(val c: Container) {
  def getFromContainer(): c.X = c.get()
}

val noTypeParam = new NoTypeParam(container)

// this does *not* compile
val bar: String = noTypeParam.getFromContainer()
Run Code Online (Sandbox Code Playgroud)

有人知道为什么需要类型参数吗?

Mil*_*bin 1

请参阅scala-internals 上的线程,特别是 Adriaan 的解释。