data class User(val name: String, val id: Int)
fun main() {
//sampleStart
val user = User("Alex", 1)
// 自动调用 toString() 函数,使输出易于阅读
println(user)
// User(name=Alex, id=1)
//sampleEnd
}
这在调试或创建日志时特别有用。
比较实例
要比较数据类的实例,可以使用等号运算符 ==:
data class User(val name: String, val id: Int)
fun main() {
//sampleStart
val user = User("Alex", 1)
val secondUser = User("Alex", 1)
val thirdUser = User("Max", 2)
// 比较 user 和 secondUser
println("user == secondUser: ${user == secondUser}")
// user == secondUser: true
// 比较 user 和 thirdUser
println("user == thirdUser: ${user == thirdUser}")
// user == thirdUser: false
//sampleEnd
}
data class User(val name: String, val id: Int)
fun main() {
//sampleStart
val user = User("Alex", 1)
val secondUser = User("Alex", 1)
val thirdUser = User("Max", 2)
// 创建 user 的精确副本
println(user.copy())
// User(name=Alex, id=1)
// 创建一个 name 为 "Max" 的 user 副本
println(user.copy("Max"))
// User(name=Max, id=1)
// 创建一个 id 为 3 的 user 副本
println(user.copy(id = 3))
// User(name=Alex, id=3)
//sampleEnd
}
// 在这里写下你的代码
fun main() {
val emp = Employee("Mary", 20)
println(emp)
emp.salary += 10
println(emp)
}
data class Employee(val name: String, var salary: Int)
fun main() {
val emp = Employee("Mary", 20)
println(emp)
emp.salary += 10
println(emp)
}
练习 2
声明该代码编译所需的额外数据类。
data class Person(val name: Name, val address: Address, val ownsAPet: Boolean = true)
// 在这里写下你的代码
// data class Name(...)
fun main() {
val person = Person(
Name("John", "Smith"),
Address("123 Fake Street", City("Springfield", "US")),
ownsAPet = false
)
}
data class Person(val name: Name, val address: Address, val ownsAPet: Boolean = true)
data class Name(val first: String, val last: String)
data class Address(val street: String, val city: City)
data class City(val name: String, val countryCode: String)
fun main() {
val person = Person(
Name("John", "Smith"),
Address("123 Fake Street", City("Springfield", "US")),
ownsAPet = false
)
}