I have several data classes which include a var id: Int? field. I want to express this in an interface or superclass, and have data classes extending that and setting this id when they are constructed. However, if I try this:

interface B {
  var id: Int?
}

data class A(var id: Int) : B(id)

它抱怨我忽略了id字段,我就是哈哈..

Q: How can I let the data class A in this case to take an id when it's constructed, and set that id declared in the interface or superclass?

推荐答案

Indeed, you needn't an abstract class yet. you can just override the interface properties, for example:

interface B {
    val id: Int?
}

//           v--- override the interface property by `override` keyword
data class A(override var id: Int) : B

interface没有构造函数,所以不能通过super(..)关键字调用构造函数,但可以使用abstract class.然而,a data class不能在其primary constructor上声明任何参数,因此它将overwritten超类的field,例如:

//               v--- makes it can be override with `open` keyword
abstract class B(open val id: Int?)

//           v--- override the super property by `override` keyword
data class A(override var id: Int) : B(id) 
//                                   ^
// the field `id` in the class B is never used by A

// pass the parameter `id` to the super constructor
//                            v
class NormalClass(id: Int): B(id)

Kotlin相关问答推荐

Jetpack Compose中的数字 Select 器问题

使用数据存储首选项Kotlin Jetpack Compose

在KMM合成多平台中创建特定于平台的视图

在调用父构造函数之前重写类属性

如何使用multiset与JOOQ获取关联的记录列表?

使用调度程序运行异步 Kotlin 代码

根据字符串值动态过滤数组列表 - kotlin

在jetpack compose中将默认方向设置为横向?

如何将 `throw` 放置在辅助函数中但仍然具有空安全性?

如何在 kotlin 中使用带有泛型的密封类

如果不为空,则为 builder 设置一个值 - Kotlin

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

为什么 IntelliJ Idea 无法识别我的 Spek 测试?

Kotlin - mutableMapOf() 会保留我输入的顺序

Kotlin 单元测试 - 如何模拟 Companion 对象的组件?

Kotlin get字段注释始终为空

如何将map函数应用于Kotlin中的数组并更改其值?

Kotlin中的函数接口

Kotlin:测试中的 java.lang.NoSuchMethodError

将协程更新到 1.2.0 后构建失败:META-INF/atomicfu.kotlin_module