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
}
这个功能在调试程序或创建 log 时, 非常有用.
比较实例
要比较数据类的实例, 请使用相等比较操作符 ==:
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 和 second user
println("user == secondUser: ${user == secondUser}")
// 输出结果为 user == secondUser: true
// 比较 user 和 third user
println("user == thirdUser: ${user == thirdUser}")
// 输出结果为 user == thirdUser: false
//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
)
}