Kotlin Data Class: 使用 constructor 扩展构造方法示例
以下是一个示例代码,展示了如何通过 'constructor' 关键字拓展 data class 的构造方法:
data class Person(val name: String, val age: Int)
// 使用 constructor 拓展构造方法
data class PersonWithAddress(val name: String, val age: Int, val address: String) {
constructor(person: Person, address: String) : this(person.name, person.age, address)
}
fun main() {
val person = Person('John', 25)
val personWithAddress = PersonWithAddress(person, '123 Main St')
println(personWithAddress)
}
在上面的例子中,我们有一个 data class 'Person',它有两个属性 'name' 和 'age'。然后我们使用 'constructor' 关键字拓展了一个新的 data class 'PersonWithAddress',它有三个属性 'name'、'age' 和 'address'。我们还定义了一个辅助构造方法,该方法接受一个 'Person' 对象和一个 'address' 字符串,并将其传递给主构造方法。
在 'main' 函数中,我们创建了一个 'Person' 对象 'person',然后使用它来创建一个 'PersonWithAddress' 对象 'personWithAddress',并传递一个地址字符串。最后,我们打印输出 'personWithAddress' 对象。
输出结果将是:'PersonWithAddress(name=John, age=25, address=123 Main St)'。
原文地址: https://www.cveoy.top/t/topic/om7S 著作权归作者所有。请勿转载和采集!