2017-05-30 138 views
2

我有一个类为什么Kotlin修饰符'open'与'data'不兼容?

open data class Person(var name: String) 

和其他类

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

这给了我一个错误,

error: modifier 'open' is incompatible with 'data'

如果我从Person类以其优良的删除数据。

为什么kotlin开放和数据不兼容?

回答

8

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:

  • 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.

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

3

作为documentation状态,

  • Data classes cannot be abstract, open, sealed or inner;

它们不能从被继承的原因是,从数据类继承导致问题/模糊度如何与他们的生成的方法(equalshashcode等)应工作。请参阅关于此here的进一步讨论。

从开始,对数据类的限制已略微提升:它们现在可以继承其他类,如相关proposal中详细描述的那样。但是,他们仍然不能从类继承。


注意, “唯一的” 数据类提供的自动equalshashcodetoStringcomponent,和copy功能额外的便利。如果你不需要这些,那么像下面这样的类仍然具有getter/setter和构造函数的属性,并且对于如何继承使用它没有限制:

class User(val name: String, var age: Int) 
相关问题