2014-07-16 206 views
0

爲什麼Scala編譯器不能推斷出Y的類型參數AInt特徵類型參數推斷

trait X[A] 

trait Y[A] extends X[A] 

object Foo extends X[Int] with Y 

有沒有一種方法,我可以做到這一點,其中Y可以瞭解的X類型參數沒有Foo的聲明,指明瞭兩次?我無法獲得自我打字的解決方案。

+1

爲什麼你不只是有'對象foo Y延伸[INT]'? –

+0

爲了擴展@ LimbSoup的答案,由於Y [A]已經擴展了X [A],所以你在X [A]中混合了兩次。有什麼特別的原因? –

+0

公平的問題。我會需要幾個'Y'類型,所以我要推遲到編譯器以合理的方式對它們進行線性化處理(我認爲這回答@ Mario的問題)。 –

回答

0

Scala不支持類型聲明中類型構造函數參數的推理(和省略)。這可能在未來的基於DOT演算的Scala版本中嘗試統一類型參數和類型成員。

參見Odersky的演講幻燈片The Trouble With Types(幻燈片29ff)的幻燈片。

0

您是否需要在此表單中輸入參數?在某些情況下,可以使用以下解決方案:

trait X { type A /* type parameter as member */ } 
trait Y extends X 
object Foo extends Y { type A = Int /* equivalent to Y[Int] or X [Int] */ } 

它可以用於定義。

trait X { 
    type A 
    def xfun: A 
} 
trait Y extends X { def tuple[K](k: K): (K, A) = (k -> xfun) } 
object Foo extends Y { 
    def xfun = System.identityHashCode(this) 
    type A = Int 
} 

那麼,如果測試:

scala> Foo.tuple("test") 
res0: (String, Foo.A) = (test,2088931356) 
1

對於一些使用情況,使用中間類可以解決這個問題:

import scala.reflect.runtime.universe._ 

abstract class XBase { 
    type A 
    def say(a : A) : Unit = println(a) 
} 

trait Y extends XBase { 
    override def say(a : A) : Unit = { 
     println("Hello ") 
     super.say(a) 
    } 
} 

class X[B : TypeTag] extends XBase { 
    type A = B 
} 

object Foo extends X[Int] with Y