-
Notifications
You must be signed in to change notification settings - Fork 785
2019-07-19:谈谈你对Kotlin中的 data 关键字的理解?相比于普通类有哪些特点? #101
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Data ClassesWe frequently create classes whose main purpose is to hold data. data class User(val name: String, val age: Int) The compiler automatically derives the following members from all properties declared in the primary constructor:
To ensure consistency and meaningful behavior of the generated code, data classes have to fulfill the following requirements:
Additionally, the members generation follows these rules with regard to the members inheritance:
Since 1.1, data classes may extend other classes (see Sealed classes for examples). On the JVM, if the generated class needs to have a parameterless constructor, default values for all properties have to be specified data class User(val name: String = "", val age: Int = 0) Properties Declared in the Class BodyNote that the compiler only uses the properties defined inside the primary constructor for the automatically generated functions. To exclude a property from the generated implementations, declare it inside the class body: data class Person(val name: String) {
var age: Int = 0
} Only the property data class Person(val name: String) {
var age: Int = 0
}
fun main() {
//sampleStart
val person1 = Person("John")
val person2 = Person("John")
person1.age = 10
person2.age = 20
//sampleEnd
println("person1 == person2: ${person1 == person2}")
println("person1 with age ${person1.age}: ${person1}")
println("person2 with age ${person2.age}: ${person2}")
} CopyingIt's often the case that we need to copy an object altering some of its properties, but keeping the rest unchanged. fun copy(name: String = this.name, age: Int = this.age) = User(name, age) This allows us to write: val jack = User(name = "Jack", age = 1)
val olderJack = jack.copy(age = 2) Data Classes and Destructuring DeclarationsComponent functions generated for data classes enable their use in destructuring declarations: val jane = User("Jane", 35)
val (name, age) = jane
println("$name, $age years of age") // prints "Jane, 35 years of age" Standard Data ClassesThe standard library provides |
看头像表情 |
看头像表情 |
我觉得把,在没有对应的插件之前,大家还是使用 Java 的 bean 类把,做大数据的,使用 data 类,估计能累到吐血,纯属个人意见,如果有更好的,请提供下方法 |
在Kotlin中,
需要注意的是,数据类有一些限制和要求,比如主构造函数至少有一个参数,且所有参数必须用 总的来说,Kotlin中的数据类为我们处理数据提供了很多便利,减少了我们编写重复的代码,增加了代码的可读性和可维护性。 |
这是来自QQ邮箱的假期自动回复邮件。
|
这是来自QQ邮箱的假期自动回复邮件。
您好,我最近正在休假中,无法亲自回复您的邮件。我将在假期结束后,尽快给您回复。
|
No description provided.
The text was updated successfully, but these errors were encountered: