以下是我试图解决的问题,我正在try 将void类型用作泛型类型:

class Parent {
    private abstract class Item<out T>(val data: T)
    // This subclass should contain data
    private class ItemContent(val data: String): Item<String>(data)
    // This subclass doesn't contain data
    private class ItemNoContent: Item<Any?>(null)
}

Some base classes like ItemNoContent doesn't contain meaningful data so I make ItemNoContent extends Item(null). It works but I feel that the use of Any? and null is inappropriate here. Is there a more Kotlin way to solve this optional generic problem?

推荐答案

You can also use Item<Unit>(Unit) which represents a void value in Kotlin.

Kotlin相关问答推荐

在Kotlin中可以连接两个范围吗?

Kotlin接口方法默认值&;可传递依赖项

Kotlin Poet 的导入不明确

Android Jetpack Compose:在空的 Compose 活动中找不到 OutlinedTextField (Material3)

修改器的属性是什么,我需要更改以使角变圆且宽度更小?喷气背包组合

判断 Kotlin 变量是否为函数

Kotlin 协程按顺序执行,但仅在生产机器上执行

我可以在 Kotlin 中使用接口类型作为构造函数参数吗

JavaFX - 你如何在 Kotlin 中使用 MapValueFactory?

Kotlin 日期格式从一种更改为另一种

Kotlin 有垃圾收集器吗?如果是这样,它基于哪种算法?

Kotlin 方法重载

创建首选项屏幕时找不到androidx.preference.PreferenceScreen

Kotlin-Java 互操作不能与可变参数一起使用

无法为 retrofit2.Call 调用无参数构造函数

Kotlin 中的内联构造函数是什么?

Kotlin:sealed class cannot "contain" data classes?

未解决的参考 dagger 2 + kotlin + android gradle

用 kotlin 学习 Android MVVM 架构组件

如何在 Kotlin 中定义新的运算符?