kotlin - 父类的初始化块中的空值
问题描述
我正在创建一个非常简单的 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
父类的变量变为空。有人可以解释这是为什么吗?我希望它为空,因为它也有默认参数"mild"
解决方案
open var
当您不覆盖任何 getter/setter 方法时,您正在使用。
您引入了奇怪的初始化冲突,因为Spice.init
在之前调用(父类构造函数)SubSpice.init
并通过覆盖它们不再与父构造函数一起初始化的字段 - 相反,一旦Subspice
构造它们,它们将可用。
open
从父类和子构造函数中的变量中删除关键字override var
,这样字段将在Spice
类中正确初始化并且其init
块应该成功运行。
推荐阅读
- python - Python + bash 提示:如何打印宽度计算包装器?
- python - Python2.7套接字错误37“操作已经在进行中”
- javascript - Amplify.service.api.get 返回 sampleCloudAPI 不存在
- lua - ROBLOX Lua - 尽管脚本中的颜色 ID 不同,但仍向玩家提供了错误的等级颜色
- python - 类型错误:需要整数参数,使用 apply() 获得浮点数
- spring-mvc - 如何将带有多个文件的 POST 请求从 Robot Framework 发送到 Spring Boot 控制器
- java - 使用共享 id 字段将两个不同的对象列表合并为一个
- r - 匹配四元变量 R
- node.js - npm start,使用有效的 SSL
- python - 连接和排序季节性时间序列的有效方法?