You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin if表达式报错问题及修正代码正确性咨询

Kotlin中if表达式报错问题及代码正确性验证

初始代码与报错

运行以下Kotlin代码时,出现报错:'if' must have both main and 'else' branches if used as an expression

初始代码如下:

var score = 76
var score_letter = if (0 < score < 50 ) {
    println("nilai $score memiliki nilai huruf D")
} else if (51 < score <= 60) {
    println("nilai $score memiliki nilai huruf C+")
} else if (61 < score <= 70) {
    println("nilai $score memiliki nilai huruf C")
} else if (71 < score <= 85) {
    println("nilai $score memiliki nilai huruf B")
} else if (86 < score <= 100) {
    println("nilai $score memiliki nilai huruf A")
}
println(score_letter)

报错核心原因:Kotlin中if作为表达式赋值给变量时,必须保证所有分支都有明确返回值,且必须包含else分支覆盖所有未定义的情况。初始代码既没有在分支中返回值,也没有兜底的else,不符合表达式语法要求。

修改后的代码正确性判断

你修改后的代码是正确的,理由如下:

  • 所有if-else分支都返回了字符串类型的值,确保表达式有明确的返回结果
  • 通过嵌套结构覆盖了所有可能的输入场景(小于0、0-50、51-60、61-70、71-85、86-100、大于100),不存在未覆盖的分支
  • 完全符合Kotlin中if作为表达式的语法规则,不会再触发原报错

修改后的代码:

var score = 101
var score_value =
    if (score <= 100) {
        if (score <= 85) {
            if (score <= 70) {
               if (score <= 60) {
                    if (score <= 50) {
                        if (score >= 0) {
                            "Skor $score mendapatkan skor huruf D"
                        } else {
                            "Skor $score dibawah 0"
                        }
                    } else {
                       "Skor $score mendapatkan skor huruf C+"
                    }
                } else {
                    "Skor $score mendapatkan skor huruf C"
                }
            } else {
                "Skor $score mendapatkan skor huruf B"
            }
        } else {
            "Skor $score mendapatkan skor huruf A"
        }
    } else {
        "Tidak dapat ditentukan"
    }

println("The Result : $score_value")

Kotlin与Python、VBA的if写法差异

Python的if-else写法(语句形式)

Python的if是语句,侧重执行逻辑,不需要强制覆盖所有分支(建议加else兜底),也不要求分支返回值:

if (condition1):
   Do Something
elif (condition2):
   Do Something
elif (condition3):
   Do Something
else:
   Do Something

Excel VBA的if-else写法(语句形式)

VBA的if同样是语句,通过ElseIf和End If闭合结构,核心作用是执行逻辑而非返回值:

if condition1 then
   do something
elseif condition2 then
   do something
elseif condition3 then
   do something
else
   do something
end if

Kotlin的核心差异

Kotlin的if具备双重特性:

  • 作为语句使用时,和Python/VBA逻辑一致,侧重执行代码块,无需强制else
  • 作为表达式使用(赋值给变量时),必须保证所有分支返回同类型值,且必须有else分支覆盖所有场景

内容的提问来源于stack exchange,提问作者spiderboy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 03:26:03