首页 > 解决方案 > 为什么子类不能访问 Kotlin 中的嵌套接口?

问题描述

在 Java 中,我可以定义一个嵌套在内部的接口MainClass,并且我仍然可以通过 any 引用该接口SubClass,如下所示:

public class MainClass {
  interface MyInterface {
    public void printName();
  }
}

public class SubClass extends MainClass {
}

// Notice here that I use `SubClass.MyInterface` so the client doesn't know MainClass exists.
public void handleInterface(SubClass.MyInterface implementation) {
}

但是,如果我尝试在 Kotlin 中做同样的事情,它就不起作用:

open class MainClass {
  interface MyInterface {
    fun printName()
  }
}

class SubClass : MainClass()

// This will not compile unless I do `MainClass.MyInterface`. See the Java notes about why I might want that.
fun handleInterface(implementation: SubClass.MyInterface) {
}

我已经有过我们不需要的辩论,SubClass.MyInterface可以从定义它的基类中引用它,但我真的很好奇为什么 Kotlin 不支持这一点,而 Java 似乎允许它。

标签: javakotlin

解决方案


推荐阅读