为什么Kotlin修饰符“打开”与“数据”不兼容? [英] Why Kotlin modifier 'open' is incompatible with 'data'?
问题描述
我有一个课程:
open data class Person(var name: String)
和另一类:
data class Student(var reg: String) : Person("")
这给了我一个错误:
错误:修饰符'open'与'data'不兼容
error: modifier 'open' is incompatible with 'data'
如果我从 Person
类中删除数据就可以了。
if I remove data from Person
class it's fine.
为什么打开Kotlin和数据不兼容?
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:
- 主构造函数必须具有至少一个参数;
- 所有原始y构造函数参数需要标记为val或var;
- 数据类不能是抽象的,打开,密封或内部的;
- (在1.1之前)数据类只能实现接口。
- The primary constructor needs to have at least one parameter;
- All primary constructor parameters need to be marked as val or var;
- Data classes cannot be abstract, open, sealed or inner;
- (before 1.1) Data classes may only implement interfaces.
因此,重点是该数据类具有一些生成的代码(等于
, hashCode
,副本
, toString
, componentN
函数)。并且此类代码不得由程序员破坏。结果,数据类具有一些限制。
So the main point is that data class has some generated code (equals
, hashCode
, copy
, toString
, componentN
functions). And such code must not be broken by the programmer. As a result, data class has some restrictions.
这篇关于为什么Kotlin修饰符“打开”与“数据”不兼容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!