2014-06-19 13 views
3

這裏已經組成是代碼:特質組成將在新的情況下被忽略,如果它是在類級別

trait Foo { 

    def get(x: Int): Int 

} 

trait Simple extends Foo { 

    override def get(x: Int): Int = x 

} 

trait Add15 extends Foo { 

    abstract override def get(x: Int): Int = x + 15 

} 

trait Add30 extends Foo { 

    abstract override def get(x: Int): Int = { 

    super.get(x) + 30 
    } 

} 


class Queue extends Simple with Add15 with Add30 

new Queue with Add30 get 0 // same as new Queue get 0, because with Add30 is ignored 

我只是想知道這是它最好有一個編譯錯誤,而不是忽略它?它就像

class Queue extends Simple with Add15 with Add30 with Add30將有一個編譯錯誤

提前

+0

的可能重複[斯卡拉:如何繼承兩次同一性狀](http://stackoverflow.com/questions/17287395/scala-how-to-inherit-the-same-trait-twice),或[繼承的性狀兩次(http://stackoverflow.com/questions/7230808/inheriting-a-trait-twice)。 – DaoWen

+1

@DaoWen IMO這是一個不同的問題:如果'Add30'是一個正常的性狀然後'與Add30'新隊列[記錄了意圖](http://stackoverflow.com/questions/4387419/why-does-arraylist-have -implements-list)Queue正在實現'Add30',但是當特徵可堆疊時它是否成立? –

+0

這是否有道理,還是不依賴於可堆疊特性的語義,這不是東西是在類型系統中捕獲的,因此禁止將排除,你可能合法地希望能夠重複性狀記錄意圖的情況下(正如@ShyamendraSolanki所說)。 –

回答

0

with非常感謝也是不可忽視的。

new tactually saysnew Queue with Add30該規範等同於:當然

{ class a extends Queue with Add30 ; new a } 

,但它實際上編譯成的?

事實上:

scala> new Queue with Add30 
res8: Queue with Add30 = [email protected] 

scala> :javap -prv - 
Binary file res8 contains $line18.$read$$iw$$iw$ 
[snip] 
    private final $line12.$read$$iw$$iw$Queue res8; 
    flags: ACC_PRIVATE, ACC_FINAL 
[snip] 
    public $line18.$read$$iw$$iw$(); 
    flags: ACC_PUBLIC 
    Code: 
     stack=3, locals=1, args_size=1 
     0: aload_0  
     1: invokespecial #19     // Method java/lang/Object."<init>":()V 
     4: aload_0  
     5: putstatic  #21     // Field MODULE$:L$line18/$read$$iw$$iw$; 
     8: aload_0  
     9: new   #23     // class $line18/$read$$iw$$iw$$anon$1 
     12: dup   
     13: invokespecial #24     // Method $line18/$read$$iw$$iw$$anon$1."<init>":()V 
     16: putfield  #17     // Field res8:L$line12/$read$$iw$$iw$Queue; 
     19: return 

因此所得到的值只是一個Queue,但你實例化平凡擴展它的匿名子類。我太懶(我的意思是忙)嘗試-optimize

您可以扭轉的問題,問爲什麼with T with T抱怨trait T is inherited twicelinearization不能處理冗餘?

我認爲第二種情況,其中a從線性消失,是如此:

scala> class X 
defined class X 

scala> trait Y extends X 
defined trait Y 

scala> new X with Y 
res15: X with Y = [email protected] 

,你在已經延伸X一個Y正在混合。

但現在我必須使用上,我被塗鴉爲它的主要用途情況下,餐巾紙(餐巾紙),並回到我在做什麼了。

相關問題