从不同的界面覆盖相同的签名

如果我们有两个接口,使用相同的签名方法,我们可以在一个类中实现它们,方法如下:

interface A { void doStuff(); } interface B { void doStuff(); } class Test : A, B { void A.doStuff() { Console.WriteLine("A"); } void B.doStuff() { Console.WriteLine("A"); } } 

如果我们把它转换成Kotlin我们有

 interface A { fun doStuff() } interface B { fun doStuff() } class Test : A, B { override fun doStuff() { println("Same for A b") } } fun main(args: Array<String>) { var test = Test(); test.doStuff() //will print Same for A b" var InterfaceA:A = test var InterfaceB:B = test InterfaceA.doStuff()//will print Same for A b" InterfaceB.doStuff()//will print Same for A b" } 

所以,我的问题是,我怎样才能给每个接口一个不同的实现,如在C犀利的例子? **注:我已阅读https://kotlinlang.org/docs/reference/interfaces.html上的文档,也有类似的例子,

 interface A { fun foo() { print("A") } } interface B { fun foo() { print("B") } } class D : A, B { override fun foo() { super<A>.foo() super<B>.foo() } } 

在这里,foo是在每个接口中实现的,所以在D中实现时,只需调用接口中定义的实现即可。 但是,我们如何给D定义不同的实现呢?

在Kotlin是不可能的。 Kotlin在这方面与Java类似。 在接口中覆盖等效的方法在类中必须具有相同的实现。 该行为背后的基本原理是,将对象引用投射到不同类型不应改变其方法的行为,例如:

 val test = Test() (test as A).doStuff() (test as B).doStuff() // should do the same as above