5

我試圖讓Scala找到來自單例類型的路徑依賴類型的正確類型。暴露來自單例類型的路徑依賴類型

首先,這裏是該示例的類型的容器,和一個實例:

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

val container = new Container { 
    type X = String 
    def get(): X = "" 
} 

我可以看到在第一次嘗試的字符串(所以我已經有一個工作方案):

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() 

但是,當沒有類型參數,這不再工作。

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() 

有人知道爲什麼需要類型參數嗎?

回答

1

請參閱this關於scala內部的線程,特別是Adriaan的解釋。