2016-09-15 63 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