gpt4 book ai didi

kotlin - 父类的init block 中的null值

转载 作者:行者123 更新时间:2023-12-02 13:03:13 25 4
gpt4 key购买 nike

我正在创建一个非常简单的kotlin程序,并且看到父类的行为很奇怪。

代码是:

fun makeSalt(name:String) = Spice(name, "non-spicy")
fun main(args: Array<String>) {
var salt : Spice = Spice("salt", "non-spicy")

println("Salt heat = ${salt.heat}")

val spicelist = listOf<Spice>(
Spice("salt", "non-spicy"),
Spice("turmeric", "mild"),
Spice("Pepper", "hot"),
Spice("Chilli", "hot"),
Spice("Sugar", "non-spicy")
)

val mildSpices = spicelist.filter{it.heat <=5}

val salt2 = makeSalt("rock salt")

val bhoot : SubSpice = SubSpice("bhoot", "hot")
}


open class Spice(open var name:String, open var spiciness:String = "mild" ){
var heat : Int = 5
get() = when (spiciness){
"mild"->5
"hot"->10
"non-spicy"->1
else -> 0

}

init{
if(spiciness === null) {println("spiciness is null")}
else println("Spiciness of ${name} = ${spiciness}; heat = ${heat}")
}
}

class SubSpice(override var name:String, override var spiciness:String = "hot") : Spice(name, spiciness){

}

当我执行此程序时,输出为:
Spiciness of salt = non-spicy; heat = 1
Salt heat = 1
Spiciness of salt = non-spicy; heat = 1
Spiciness of turmeric = mild; heat = 5
Spiciness of Pepper = hot; heat = 10
Spiciness of Chilli = hot; heat = 10
Spiciness of Sugar = non-spicy; heat = 1
Spiciness of rock salt = non-spicy; heat = 1
spiciness is null

如您所见,当我创建子类的对象时,父类的变量 spiciness变为空。有人可以解释为什么吗?我期望它为null,因为它也具有 "mild"的默认参数

最佳答案

当您不覆盖任何getter / setter方法时,就在使用open var

您正在引入奇怪的初始化冲突,因为在Spice.init之前调用了SubSpice.init(父类构造函数),并且通过覆盖它们不再与父构造函数一起初始化的字段-相反,一旦构造了Subspice,它们将可用。

从父类中的变量和子构造函数中的open中删除override var关键字,这样字段将在Spice类中正确初始化,并且其init块应成功运行。

关于kotlin - 父类的init block 中的null值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57989947/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com