Kotlin的抽象超类中的内部类? [英] Inner class within its abstract superclass in Kotlin?

查看:186
本文介绍了Kotlin的抽象超类中的内部类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果一组内部类是其外部抽象包含类的唯一实现(子类),那么如何实例化它们?

If a set of inner classes are the only implementations (subclasses) of their outer abstract containing class, how does one instantiate them?

abstract class A {
    inner class A1 : A()
    inner class A2 : A()
}

换句话说,构造A1A2实例的语法是什么?

In other words, what is the syntax to construct an instance of A1 or A2?

编辑:在A类正文之外.

推荐答案

您在寻找这个吗?

abstract class A {
    fun doSome() { // OK
        val a1 = A1()
        val a2 = A2()
    }
    inner class A1 : A()
    inner class A2 : A()
}

我认为您可能想在A之外构造A1/A2的实例,例如:

I think you probably want to construct instances of A1/A2 outside of A, like:

abstract class A {
    inner class A1 : A()
    inner class A2 : A()
}
fun doSome() { // Error
    val a1 = A1()
    val a2 = A2()
}

在Kotlin和Java中都不允许这样做,因为内部类持有外部类的角色.如果要在A之外构造A1/A2,只需删除inner修饰符即可.

This is not allowed in both Kotlin and Java, because inner class holds ponters to the outer class. If you want to construct A1/A2 outside of A, simply remove the inner modifiers.

abstract class A {
    class A1 : A()
    class A2 : A()
}

fun doSome() { // OK again
    val a1 = A.A1()
    val a2 = A.A2()
}

此外,因为您说的是

一组内部类是其外部抽象包含类的唯一实现(子类)

a set of inner classes are the only implementations (subclasses) of their outer abstract containing class

您可以将abstract修饰符替换为sealed.这将帮助Kotlin对when表达式进行彻底检查.

You can replace abstract modifier with sealed. This will help Kotlin do exhautiveness check in when expression.

这篇关于Kotlin的抽象超类中的内部类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆