I have a class:

open data class Person(var name: String)

and another class:

data class Student(var reg: String) : Person("")

this gives me an error that:

错误:修饰符"打开"与"数据"不兼容

如果我从Person类中删除数据,那就没问题了.

why kotlin open and data incompatible?

推荐答案

https://kotlinlang.org/docs/reference/data-classes.html:

To ensure consistency and meaningful behavior of the generated code, data classes have to fulfil the following requirements:

  • 主构造函数需要至少有一个参数;
  • All primary constructor parameters need to be marked as val or var;
  • 数据类不能是抽象的、open的、密封的或内部的;
  • (1.1之前)数据类只能实现接口.

所以主要的一点是数据类有一些生成的代码(equalshashCodecopytoStringcomponentN函数).这样的代码不能被程序员 destruct .因此,数据类有一些限制.

Kotlin相关问答推荐

在Kotlin中处理结果的高阶函数

我可以检测一个函数是否在Kotlin中被递归调用(即,重入)吗?

Spring Boot Bean验证器未触发

带有Spring Boot和Kotline的可嵌入实体

在Webflux应用程序中通过kotlin协程启动fire and forget job

Kotlin stlib中是否有用于将列表<;对<;A,B&>;转换为对<;列表<;A&>,列表<;B&>;的函数

为什么我的通用Kotlin函数中的这个转换未经判断?

Rabin-Karp字符串匹配的实现(Rolling hash)

Kotlin 中获取类简单名称的最佳实践

使用最新的 com.jakewharton.rxbinding3:rxbinding:3.0.0-alpha2 库时未找到 RxTextView 和其他小部件

Kotlin Compose,在行中对齐元素

如何处理 Kotlin 中的异常?

如果我可以将 Flow 和 StateFlow 与生命周期范围 \ viewLifecycleOwner.lifecycleScope 一起使用,那么在 ViewModel 中使用 LiveData 有什么意义

Jetpack Compose State:修改类属性

从 Spring WebFlux 返回 Flux 返回一个字符串而不是 JSON 中的字符串数组

如何使用kotlin中的反射查找包中的所有类

如何将 CameraView 与 Jetpack Compose 一起使用?

Kotlin类型安全类型别名

在 Android 12 (SDK 31) 中获取 android.app.ForegroundServiceStartNotAllowedException

如何在 Kotlin 中按字母顺序对字符串进行排序