1、Kotlin中的数据类主要用于保存数据。对于每个数据类,编译器会自动生成其他成员函数,允许您将实例打印到可读输出、比较实例、复制实例等。
中文文档:
https://book.kotlincn.net/text/data-classes.html
2、新建文件dataClassTest.kt
3、代码
data class User1(val name: String, val age: Int)
fun main(args: Array<String>) {
val jack = User1(name = "Jack", age = 1)
val olderJack = jack.copy(age = 2)
println(jack)
println(olderJack)
val jane = User1("Jane", 35)
val (name, age) = jane
println("$name, $age years of age") // prints "Jane, 35 years of age"
}
4、kotlin的数据类,声明简单方便,还可以在类体中声明属性:
data class Person(val name: String) {
var age: Int = 0
}
fun main() {
val person1 = Person("John")
val person2 = Person("John")
person1.age = 10
person2.age = 20
println("person1 == person2: ${person1 == person2}")
// person1 == person2: true
println("person1 with age ${person1.age}: ${person1}")
// person1 with age 10: Person(name=John)
println("person2 with age ${person2.age}: ${person2}")
// person2 with age 20: Person(name=John)
}
5、类体中声明属性的输出:
6、复制
fun main(args: Array<String>) {
val jack = UserCopy(name = "Jack", age = 1)
val olderJack = jack.copy(age = 2)
println(olderJack)
}
7、复制的输出