我想将现有父类的值转移到新的子类。如果可能的话,不要反思。另一个可能的解决方案是,如果我可以"cast";类的子类。
这是我想要实现的一个简化的例子。
open class Dog {
var height = -1
}
class Dalmatian: Dog() {
var dots = -1
}
fun main() {
val dog: Any = Dog().apply {
height = 24
}
// Doesn't work
val dalmatian = (dog as Dalmatian).apply {
dots = 101
}
}
没有内置的方法将类转换为子类型。在您的例子中,您可以创建一个方法:
class Dog(var height: Int = -1)
class Dalmation(height: Int = -1, var dots: Int = 24): Dog(height) {
companion object {
fun fromDog(dog: Dog, dots: Int) = Dalmation(dog.height, dots)
}
}
可以转换为:
fun main() {
val dog = Dog()
val dalmation = Dalmation.fromDog(dog, 24)
}
,只有当狗已经是一只狗时,你才能施放:
fun main() {
val dog: Dog = Dalmatian()
val dalmatian: Dalmatian = dog as Dalmatian
// but not this
val dalmatian: Dalmatian = Dog() as Dalmatian
}