在Java中,我可以定义嵌套在MainClass
内的接口,并且仍然可以通过任何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似乎支持允许它。