【问题标题】:Overriding same signature from different interfaces覆盖来自不同接口的相同签名
【发布时间】:2017-10-20 07:29:11
【问题描述】:

在 C sharp 中,如果我们有 2 个接口,具有相同的签名方法,我们可以在一个类中实现它们,方式如下:

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 sharp 示例中的?。 **注意:我已经阅读了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 中定义不同的实现呢?

【问题讨论】:

  • 请重新格式化您的示例代码(添加缩进)
  • 现在好点了吗@voddan?

标签: oop interface kotlin


【解决方案1】:

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

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

【讨论】:

  • Altho 不代表扩展功能:P
猜你喜欢
  • 1970-01-01
  • 2017-02-16
  • 1970-01-01
  • 2018-07-19
  • 2015-07-09
  • 2013-02-07
  • 2020-03-08
  • 1970-01-01
  • 2017-06-02
相关资源
最近更新 更多