2017-05-30 142 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) 
相關問題