Kotlin 变量用法 "variable must be initialize"

Kotlin variable usage "variable must be initialize"

有人可以解释一下可以在 kotlin 中解决这个问题吗?非常感谢

var weight = rweight.text.toString().toFloat()
var hct = rhct.text.toString().toFloat()
var EBV :Float
var ABL :Float

if (rman.isChecked){
    EBV = weight * 75
} else if (rwoman.isChecked) {
    EBV = weight * 65
}
ABL = EBV * (10)/hct  //error in here "EBV must be initialize"

您收到该错误是因为 EBV 在使用时可能未初始化。

您应该使用默认值初始化 EBV 变量:

var EBV: Float = 0.0f // or some other default value

或在条件中添加else子句:

EBV = if (rman.isChecked) {
    weight * 75
} else if (rwoman.isChecked) {
    weight * 65
} else {
    0.0f // assign some value to the variable
}

// As improvement you can replace `if` with `when` statement:

EBV = when {
    rman.isChecked -> weight * 75
    rwoman.isChecked -> weight * 65
    else -> 0.0f // assign some value to the variable
}