Kotlin变量用法“变量必须初始化”

时间:2020-07-27 05:49:36

标签: variables kotlin initialization

有人可以解释可以解决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"

1 个答案:

答案 0 :(得分:1)

您收到该错误,因为使用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
}