内部类继承Kotlin

时间:2016-02-26 12:32:11

标签: kotlin

我试图创建一个包含少量类的层次结构,每个类都覆盖它的父类内部类中的某些行为(特别是迭代器,但这并不重要)。基本上,它看起来像这样:

open class SuperClass<T>{
    protected open inner class InnerClass{
        fun someLogic(){
            println("some logic happened")
        }

        open fun someOverridableLogic(){
            println("some logic happened")
        }
    }
}

class ChildClass<T> : SuperClass<T>(){
    protected inner class ChildInnerClass:InnerClass{
        override fun someOverridableLogic(){
            super.someOverridableLogic()
            println("some OTHER logic happened")
        }
    }
}

编译器拒绝使用此代码,当ChildInnerClass继承它时,期望InnerClass上的类型参数。但是,在添加如下参数后:

protected inner class ChildInnerClass:InnerClass<T>

编译器突然期望任何类型参数!

相当于Java的Java编译并按预期执行,没有类型参数:

public class SuperClass<T> {
    protected class InnerClass{
        public void someLogic(){
            System.out.println("some logic happened");
        }

        public void someOverridableLogic(){
            System.out.println("some logic happened");
        }
    }
}


public class ChildClass<T> extends SuperClass<T>{
    protected class ChildInnerClass extends InnerClass{
        @Override
        public void someOverridableLogic() {
            super.someOverridableLogic();
            System.out.println("some OTHER logic happened");
        }
    }
}

所以,我在Kotlin做错了什么,还是仅仅是一种我不知道的语言限制?

1 个答案:

答案 0 :(得分:5)

编译器不期望InnerClass上的类型参数,而是SuperClass中的SuperClass.InnerClass上的类型参数。这是一个众所周知的问题:Capture generics in inner classes : KT-9208

现在您可以执行以下操作:

open class SuperClass<T> {
    protected open inner class InnerClass {
        fun someLogic() {
            println("some logic happened")
        }

        open fun someOverridableLogic() {
            println("some logic happened")
        }
    }
}

class ChildClass<T> : SuperClass<T>() {
    protected inner class ChildInnerClass : SuperClass<T>.InnerClass() {
        override fun someOverridableLogic() {
            super.someOverridableLogic()
            println("some OTHER logic happened")
        }
    }
}

有关类似示例和答案,另请参阅Hadoop Context type parameters in Kotlin