2016-09-15 81 views
0

我有三個特點,我想強制其中一個叫它C來混合特質AB。即使我知道如何強制B混合A,我也無法做到。它可以做這樣的:如何強制一個特質來實現另一個特質

trait A { 
    def getThree() = 3 
} 

trait B { 
    this: A => 
    def getFive() = 2 + getThree() 
} 

trait C { 
    this: A => // that's the line which 
    // this: B => // this line is incorrect as I there is "this: A =>" already 
    // def getEight() = getThree() + getFive() // I want this line to compile 
} 

因此我可以調用該函數getEight()

object App { 
    def main(args: Array[String]): Unit = { 

    val b = new B with A {} 
    println(b.getFive()) 

    // It would be cool to make these two lines work as well 
    // val c = new C with B with A {} 
    // println(c.getEight())  
    } 
} 
+0

'這樣的:A和B =>' –

回答

1

您可以使用with

trait C { 
self: A with B => 
} 
+0

莫非你解釋你爲什麼使用'self'而不是我的'this'? – GA1

+1

@ GA1'this'用於指上下文中的當前對象。爲了清晰起見,使用自我。 – pamu

+1

'this'應該用在這個上下文中,因爲沒有理由引入另一個自我類型的引用。當需要區分不同的'this'實例時,使用替代自我類型引用,特別是在嵌套類的情況下。 – Haspemulator