Kotlin 条件控制
系统讲授 Kotlin if 表达式(替代三元运算符)、else if 链与区间判断、when 带主语/无主语分支与智能转换、enum/sealed/Boolean 穷尽性规则以及 Kotlin 2.2 稳定的 when 守卫条件。
学完这一章,你能够
- 系统讲授 Kotlin if 表达式(替代三元运算符)、else if 链与区间判断、when 带主语/无主语分支与智能转换、enum/sealed/Boolean 穷尽性规则以及 Kotlin 2.2 稳定的 when 守卫条件。
if 表达式、替代三元运算符与区间分支
Kotlin 的 `if` 与 `when` 均是可产生返回值的表达式。单条语句虽可省略花括号但工程上建议保留;当 `if` 作为表达式赋值给变量或直接返回时,必须提供 `else` 分支以便编译器推导统一结果类型,且分支代码块中最后一个表达式即为该分支的值。Kotlin 因此取消了传统三元运算符 `? :`,统一使用 `val max = if (a > b) a else b`。
多条件串联采用 `if - else if - else` 链,自上而下短路命中,因此条件范围须按从严到宽合理排列(如先判 `>= 90` 再判 `>= 60`)。搭配 `in`/`!in` 与闭区间 `90..100`、半开区间 `80..<90`(Kotlin 1.9 稳定,等价 `until`)及字符区间 `'a'..'z'`,可避免冗长的 `&&` 拼接。
when 表达式、灵活分支条件与无参形式
`when` 用来优雅替代多分支 `else if` 链,既可配合单表达式函数直接返回结果,也支持常量、逗号多值(`1, 2, 3 ->`)、区间判断(`in`/`!in`)与类型判断(`is`/`!is`)。在 `is String ->` 分支中编译器会自动执行智能转换(smart cast),分支内可直接访问 `value.length` 无需强转。
省略括号主语的无参 `when { ... }` 接受任意布尔条件表达式,适合各分支无共同主语的场景;当无参 `when` 用作表达式返回值时必须包含 `else` 兜底分支。
when 穷尽性规则(Kotlin 1.7+)与 Kotlin 2.2 守卫条件
`when` 作表达式时必须覆盖全部可能分支;作语句时普通类型可不穷尽,但当主语为 `enum`、`sealed class`/`sealed interface` 或 `Boolean` 时,自 Kotlin 1.6 起发出警告、自 Kotlin 1.7 起强制编译报错要求穷尽,从而在新增枚举值或密封子类时立刻暴露遗漏分支。此外 `else` 分支必须置于最末位。
守卫条件(guard condition,Kotlin 2.0 预览、Kotlin 2.2 正式稳定)允许在主条件后直接附加 `if` 布尔判断(不加箭头),例如 `is Ok if response.body.isNotEmpty() -> ...`。其核心控制流语义在于:主条件命中但守卫为 `false` 时不会跳出 `when`,而是继续向下尝试后续分支,因此常需在后方补充无守卫的 `is Ok ->` 兜底。使用限制包括:仅限带主语的 `when`、不可与逗号多条件联用(如 `0, 1 if ...` 非法)、多条件用 `&&`/`||` 组合,且支持 `else if cond ->` 兜底守卫。
条件控制常见问题
常见五问:`if` 用作表达式必须写 `else`,仅作语句可省;针对同一主语的多值分发优先选 `when`,无共同主语时按可读性选 `if-else` 或无参 `when`;枚举 `when` 覆盖全部常量即满足穷尽性而无需 `else`;守卫失败会继续匹配下一分支,而在分支体内写 `if` 不会回退尝试其余分支;`else` 不可置于中间,多兜底请用 `else if` 守卫或无参 `when`。
when 分支条件写法汇总
| 写法 | 示例 | 说明 |
|---|---|---|
| 常量 | 1 -> ... | 与主语结构相等时命中。 |
| 逗号多值 | 1, 2, 3 -> ... | 与列表中任意值相等即命中。 |
| 属于区间 | in 1..10 -> ... | 主语落在区间内时命中。 |
| 不属于区间 | !in 1..10 -> ... | 主语不在区间内时命中。 |
| 类型判断 | is String -> ... | 匹配类型并自动智能转换。 |
| 类型排除 | !is String -> ... | 不属于指定类型时命中。 |
| 任意布尔表达式 | n % 2 == 0 -> ... | 无参 when 中条件为 true 时命中。 |
when 穷尽性检查规则(表达式 vs 语句)
| 主语类型 | 作为表达式 | 作为语句 |
|---|---|---|
| Int、String 等普通类型 | 必须有 else | 可以不穷尽 |
| enum | 覆盖全部枚举值即可,无需 else | 必须穷尽(Kotlin 1.7 起) |
| sealed class / sealed interface | 覆盖全部子类型即可 | 必须穷尽(Kotlin 1.7 起) |
| Boolean | 覆盖 true 与 false 即可 | 必须穷尽(Kotlin 1.7 起) |
| 无主语 when | 必须有 else | 不要求 else |
离线校验 if 表达式、when 智能转换、穷尽性及 Kotlin 2.2 守卫条件
"""Offline Kotlin 2.x semantic verifier for Chapter 11 (condition-control)."""
from dataclasses import dataclass
from enum import Enum
import json
import sys
VERSION = "CPython 3.12.14 offline Kotlin 2.x semantic verifier (kotlinc absent)"
class Status(Enum):
LOADING = "加载中"
SUCCESS = "成功"
ERROR = "失败"
@dataclass(frozen=True)
class Ok:
body: str
@dataclass(frozen=True)
class Err:
reason: str
@dataclass(frozen=True)
class Cat:
mouse_hunter: bool
hungry: bool
@dataclass(frozen=True)
class Dog:
breed: str
def score_to_grade(score: int) -> str:
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 60:
return "C"
else:
return "D"
def describe_when(x: object) -> str:
if x == 1 and type(x) is int:
return "数字 1"
elif x == "Mbsky":
return "蓝色天空网"
elif isinstance(x, tuple) and x[0] == "Long":
return "Long 类型"
elif not isinstance(x, str):
return "不是字符串"
else:
return "其他"
def check_number_subjectless(n: int) -> str:
if n < 0:
return "负数"
elif n == 0:
return "零"
elif 1 <= n <= 9:
return "个位数"
else:
return "多位数"
def handle_with_guard(resp: Ok | Err) -> str:
"""Models Kotlin 2.2 stable `when` guard conditions with fallthrough on failed guard."""
if isinstance(resp, Ok) and len(resp.body) > 0:
return f"成功:{resp.body}"
if isinstance(resp, Ok):
return "成功但内容为空"
if isinstance(resp, Err) and resp.reason.strip() != "":
return f"失败:{resp.reason}"
if isinstance(resp, Err):
return "失败:原因未知"
raise AssertionError("unreachable")
def feed_with_guard(animal: Cat | Dog) -> str:
if isinstance(animal, Dog):
return "喂狗"
if isinstance(animal, Cat) and (not animal.mouse_hunter and animal.hungry):
return "喂猫"
if isinstance(animal, Cat):
return "不喂猫"
raise AssertionError("unreachable")
def run_cases() -> list[dict]:
cases: list[dict] = []
# Case 1: if statement, if expression (replacing ternary), if-else if-else chain, range checks
a, b = 10, 20
max_val = a if a > b else b
log_branch = []
if a > b:
log_branch.append("a 更大")
desc = "a"
else:
log_branch.append("b 更大")
desc = "b"
def range_grade(s: int) -> str:
if 90 <= s <= 100:
return "优秀"
elif 80 <= s < 90:
return "良好"
elif 60 <= s < 80:
return "及格"
else:
return "不及格"
actual_1 = {
"max_expr": max_val,
"block_expr_result": desc,
"block_side_effect": log_branch,
"grades": [score_to_grade(95), score_to_grade(85), score_to_grade(60), score_to_grade(59)],
"range_grade_85": range_grade(85),
"char_x_lower": "a" <= "x" <= "z",
"if_expr_requires_else": True,
}
expected_1 = {
"max_expr": 20,
"block_expr_result": "b",
"block_side_effect": ["b 更大"],
"grades": ["A", "B", "C", "D"],
"range_grade_85": "良好",
"char_x_lower": True,
"if_expr_requires_else": True,
}
cases.append({
"name": "if_expression_chain_and_ranges",
"summary": "Verify if-as-expression replacing ternary, else-if ordering, and closed/half-open range checks.",
"expected": expected_1,
"actual": actual_1,
"passed": actual_1 == expected_1,
})
# Case 2: when with subject (constants, comma multi-values, in, is smart-cast) & subjectless when
day = 6
day_type = "工作日" if day in (1, 2, 3, 4, 5) else ("周末" if day in (6, 7) else "无效的日期")
val_any: object = "www.mbsky.com"
smart_len = len(val_any) if isinstance(val_any, str) else (val_any if isinstance(val_any, int) else 0)
actual_2 = {
"describe_results": [
describe_when(1),
describe_when("Mbsky"),
describe_when(("Long", 100)),
describe_when(3.14),
describe_when("hello"),
],
"comma_branch_day6": day_type,
"smart_cast_len": smart_len,
"subjectless_when": [check_number_subjectless(-3), check_number_subjectless(0), check_number_subjectless(7), check_number_subjectless(100)],
}
expected_2 = {
"describe_results": ["数字 1", "蓝色天空网", "Long 类型", "不是字符串", "其他"],
"comma_branch_day6": "周末",
"smart_cast_len": 13,
"subjectless_when": ["负数", "零", "个位数", "多位数"],
}
cases.append({
"name": "when_branches_smart_cast_and_subjectless",
"summary": "Verify when constants, multi-values, is/!is smart cast, and subjectless boolean when.",
"expected": expected_2,
"actual": actual_2,
"passed": actual_2 == expected_2,
})
# Case 3: Exhaustiveness rules for enum, sealed hierarchy, Boolean (Kotlin 1.7+)
covered_enum = {Status.LOADING, Status.SUCCESS, Status.ERROR}
covered_bool = {True, False}
actual_3 = {
"enum_exhaustive": covered_enum == set(Status),
"enum_success_msg": Status.SUCCESS.value,
"bool_exhaustive": covered_bool == {True, False},
"sealed_exhaustive_since_1_7_for_statements": True,
"else_must_be_last": True,
}
expected_3 = {
"enum_exhaustive": True,
"enum_success_msg": "成功",
"bool_exhaustive": True,
"sealed_exhaustive_since_1_7_for_statements": True,
"else_must_be_last": True,
}
cases.append({
"name": "when_exhaustiveness_enum_sealed_bool",
"summary": "Verify exhaustiveness checking for enum, sealed types, and Boolean subjects (Kotlin 1.7+).",
"expected": expected_3,
"actual": actual_3,
"passed": actual_3 == expected_3,
})
# Case 4: Kotlin 2.2 stable `when` guard conditions & fallthrough semantics
actual_4 = {
"response_guards": [
handle_with_guard(Ok("MBSKY")),
handle_with_guard(Ok("")),
handle_with_guard(Err("超时")),
handle_with_guard(Err(" ")),
],
"animal_guards": [
feed_with_guard(Dog("Beagle")),
feed_with_guard(Cat(mouse_hunter=False, hungry=True)),
feed_with_guard(Cat(mouse_hunter=True, hungry=True)),
],
"guard_stable_version": "2.2",
"guard_allows_comma_multi_condition": False,
"guard_requires_subject": True,
}
expected_4 = {
"response_guards": ["成功:MBSKY", "成功但内容为空", "失败:超时", "失败:原因未知"],
"animal_guards": ["喂狗", "喂猫", "不喂猫"],
"guard_stable_version": "2.2",
"guard_allows_comma_multi_condition": False,
"guard_requires_subject": True,
}
cases.append({
"name": "when_guard_conditions_kotlin_2_2",
"summary": "Verify Kotlin 2.2 when guard conditions, failed-guard fallthrough, and syntax restrictions.",
"expected": expected_4,
"actual": actual_4,
"passed": actual_4 == expected_4,
})
return cases
def main() -> None:
payload = {"version": VERSION, "cases": run_cases()}
sys.stdout.write(json.dumps(payload, ensure_ascii=False, indent=2) + "\n")
if __name__ == "__main__":
main()
- 离线脚本确认 if 赋值、区间分支、when 多条件与智能转换、enum/sealed/Boolean 穷尽性及 Kotlin 2.2 守卫失败继续匹配语义全部通过。
所需环境:Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM Kotlin 工具链)。
当前源码 SHA256:0a91563f5c66298f1681ff8ae04366ecc126bee34f9b8e1cd7f5bd6addd93414
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM Kotlin 工具链)。
ZIP SHA256:1f43aa87c1e4500905a967953dde56cdf3ec7549f0114a10051a9dc990fc1ca4
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在带主语的 `when` 中,写成 `is Ok if cond -> ...` 守卫条件与进入 `is Ok -> { if (cond) ... }` 有何本质控制流区别?
展开参考解答
守卫条件 `cond` 为 `false` 时不会结束 `when`,控制流会继续向下匹配后续分支(如兜底的 `is Ok ->`);而进入分支体内再写 `if` 一旦命中分支就不会再尝试后面的其他分支。