蓝色天空.知识 · 实践 · 创造
我的收藏
Kotlin 教程目录 43章
Kotlin / LEARN BY DOING

Kotlin 循环控制

讲解 Kotlin for 迭代与区间优化、indices/withIndex/Map 解构、while 与 do...while、break/continue 标签跳转、Kotlin 2.2 非局部 break/continue 以及 return@forEach 隐式标签。

学完这一章,你能够

  • 讲解 Kotlin for 迭代与区间优化、indices/withIndex/Map 解构、while 与 do...while、break/continue 标签跳转、Kotlin 2.2 非局部 break/continue 以及 return@forEach 隐式标签。

for 循环、区间步长优化与下标/Map 解构遍历

Kotlin 移除了传统 C/Java 三段式 `for (int i = 0; i < n; i++)`,统一以 `for (element in iterable)` 遍历任何提供 `iterator()` 的集合、数组(包括无装箱的 `IntArray`)或区间,元素类型由编译器自动推断,杜绝了漏写计数器自增导致的死循环。

遍历数字序列时可组合 `..`(闭区间)、`until` / `..<`(Kotlin 1.9 稳定半开区间)、`downTo`(递减)与正整数 `step`。性能上,直接写 `for (i in 1..1000)` 会被编译器优化为基于基本整型的计数循环而不分配对象;但若先写 `(1..1000).toList()` 再遍历则会真实分配包含 1000 个元素的列表。

需要下标时可遍历 `list.indices`(下标区间)或调用 `list.withIndex()` 配合解构声明 `for ((index, value) in sites.withIndex())`;遍历 `Map` 同样支持直接解构键值对 `for ((key, value) in info)`。

while 循环与 do...while 循环

`while` 属于先判条件再执行的循环,适合迭代次数依赖运行时状态的场景;若初始条件即为 `false`,循环体一次也不会执行。

`do...while` 先执行一次循环体再检测条件,因此循环体至少执行一次,适合先读输入或先尝试一次再决定是否重试的逻辑。(技术澄清:在 Kotlin 正式语法中,换行后的 `do { ... } while (cond)` 并不强制要求末尾分号,源文示例代码本身也未加分号;Kotlin 中真正强制使用分号分隔的是 `enum class` 枚举常量列表与类成员声明之间。)

break/continue、标签跳转与 Kotlin 2.2 非局部跳转

无标签的 `break` 与 `continue` 仅作用于最内层循环。在循环或 Lambda 前附加 `标签@`(如 `loop@ for (...)`、`check@{ ... }`)后,可通过 `break@loop` / `continue@loop` 直接跳出或继续外层嵌套循环,或通过 `return@check` 仅从对应 Lambda 返回而不影响外层函数;建议为标签选用 `outer@`、`rows@` 等具语义的名称。

自 Kotlin 2.1 预览(需 `-Xnon-local-break-continue`)并于 Kotlin 2.2 正式稳定(KT-1436)起,传给内联函数(如 `run`、`let`)的 Lambda 内可直接编写非局部 `break` 与 `continue` 作用于外层循环(例如 `val value = number ?: run { continue }`),无需再借助标志变量绕行。但若 Lambda 被保存到变量或传给非内联普通函数,则依然禁止非局部跳转。

return、隐式标签 return@forEach 与常见问题

`forEach` 是标准库内联函数:在其 Lambda 中直接写无标签 `return` 会直接从外层包含函数返回(非局部返回);若仅想跳过当前元素继续下一次遍历,应使用带隐式函数名标签的 `return@forEach`,其效果等价于 `for` 循环中的 `continue`。日常循环常见问题汇总于下方速查表。

Kotlin 循环区间与步长对比

写法含义遍历结果
1..5闭区间,包含左右两端1 2 3 4 5
1 until 5左闭右开,不包含右端1 2 3 4
5 downTo 1从大到小递减5 4 3 2 1
1..10 step 2指定正步长 2,仅取奇数1 3 5 7 9
1..<5半开区间,等价 until,Kotlin 1.9 起稳定1 2 3 4

跳转表达式对比

跳转表达式作用典型场景
break终止最近(或指定标签)的循环命中目标后提前退出遍历。
continue跳过本次迭代进入下一次过滤不满足条件的当前元素。
return从最近的外层具名函数返回(带 @标签则只返回对应 Lambda)结束函数执行并带回结果或跳过 forEach 当前项。

循环控制常见问题速查

问题说明
for 循环里的区间会创建对象吗直接遍历 1..10 会被编译优化为计数循环,不创建列表对象;先 .toList() 再遍历则会真实分配集合。
在 forEach 里写 continue 报错forEach 参数是 Lambda 块而非循环语句本身,需改用 return@forEach 或改为普通 for 循环。
do...while 后面为什么有分号(勘误说明)勘误:Kotlin 正式语法中换行后的 do...while 并不强制末尾分号(不同于 C/Java);Kotlin 真正必须写分号的位置是枚举常量与成员声明之间。
标签写在哪里标签紧贴在被标记的循环或 Lambda 之前,如 loop@ for (...) 或 name@ { ... }。
非局部 break 在旧版本报错内联 Lambda 中的非局部 break/continue 在 2.1 为预览、2.2 起稳定,旧版本请改用标签返回或状态标志。

离线校验 for/indices/withIndex、while/do-while、标签跳转及 Kotlin 2.2 非局部跳转

含完整源码 · 221 行
展开查看收起
python
"""Offline Kotlin 2.x semantic verifier for Chapter 12 (loop-control)."""
import json
import sys

VERSION = "CPython 3.12.14 offline Kotlin 2.x semantic verifier (kotlinc absent)"


class _BreakOuter(Exception):
    pass


class _ContinueOuter(Exception):
    pass


class _NonLocalReturn(Exception):
    def __init__(self, value: object = None) -> None:
        self.value = value


def run_cases() -> list[dict]:
    cases: list[dict] = []

    # Case 1: for loop over collections, arrays, ranges, indices, withIndex, Map destructuring
    sites = ["Mbsky", "www.mbsky.com", "MBSKY"]
    numbers = [10, 20, 30]
    info = {"name": "Mbsky", "site": "www.mbsky.com"}
    actual_1 = {
        "for_list": [s for s in sites],
        "for_int_array": [f"当前元素:{n}" for n in numbers],
        "closed_1_3": list(range(1, 4)),
        "until_1_3": list(range(1, 3)),
        "downTo_3_1": list(range(3, 0, -1)),
        "step_1_6_2": list(range(1, 7, 2)),
        "open_end_1_3": list(range(1, 3)),
        "indices": [f"{i}->{sites[i]}" for i in range(len(sites))],
        "with_index": [f"{i}: {v}" for i, v in enumerate(sites)],
        "map_destructure": [f"{k} = {v}" for k, v in info.items()],
    }
    expected_1 = {
        "for_list": ["Mbsky", "www.mbsky.com", "MBSKY"],
        "for_int_array": ["当前元素:10", "当前元素:20", "当前元素:30"],
        "closed_1_3": [1, 2, 3],
        "until_1_3": [1, 2],
        "downTo_3_1": [3, 2, 1],
        "step_1_6_2": [1, 3, 5],
        "open_end_1_3": [1, 2],
        "indices": ["0->Mbsky", "1->www.mbsky.com", "2->MBSKY"],
        "with_index": ["0: Mbsky", "1: www.mbsky.com", "2: MBSKY"],
        "map_destructure": ["name = Mbsky", "site = www.mbsky.com"],
    }
    cases.append({
        "name": "for_ranges_indices_and_destructuring",
        "summary": "Verify for loops over lists/arrays/ranges, indices, withIndex(), and Map destructuring.",
        "expected": expected_1,
        "actual": actual_1,
        "passed": actual_1 == expected_1,
    })

    # Case 2: while (0+ iterations) vs do...while (1+ iterations)
    countdown: list[int] = []
    c = 3
    while c > 0:
        countdown.append(c)
        c -= 1
    zero_while_runs = 0
    c0 = 0
    while c0 > 0:
        zero_while_runs += 1
        c0 -= 1
    do_while_log: list[int] = []
    cd = 0
    while True:
        do_while_log.append(cd)
        cd += 1
        if not (cd < 0):
            break
    actual_2 = {
        "while_countdown": countdown,
        "while_false_initial_runs": zero_while_runs,
        "do_while_runs_once": do_while_log,
        "do_while_final_count": cd,
    }
    expected_2 = {
        "while_countdown": [3, 2, 1],
        "while_false_initial_runs": 0,
        "do_while_runs_once": [0],
        "do_while_final_count": 1,
    }
    cases.append({
        "name": "while_and_do_while_execution",
        "summary": "Verify while pre-check (0 iterations when false) vs do...while post-check (at least 1 iteration).",
        "expected": expected_2,
        "actual": actual_2,
        "passed": actual_2 == expected_2,
    })

    # Case 3: break, continue, labeled break@loop / continue@loop, and labeled lambda return@check
    basic_jump: list[int] = []
    for i in range(1, 11):
        if i == 3:
            continue
        if i > 5:
            break
        basic_jump.append(i)

    labeled_pairs: list[str] = []
    try:
        for i in range(1, 4):
            try:
                for j in range(1, 4):
                    if j == 2:
                        raise _ContinueOuter()
                    if i == 3:
                        raise _BreakOuter()
                    labeled_pairs.append(f"i={i},j={j}")
            except _ContinueOuter:
                continue
    except _BreakOuter:
        pass

    def labeled_lambda_check(value: int) -> str:
        if value < 0:
            return "负数"  # return@check
        return "非负数"

    actual_3 = {
        "basic_break_continue": basic_jump,
        "labeled_loop_pairs": labeled_pairs,
        "labeled_lambda": [labeled_lambda_check(5), labeled_lambda_check(-1)],
    }
    expected_3 = {
        "basic_break_continue": [1, 2, 4, 5],
        "labeled_loop_pairs": ["i=1,j=1", "i=2,j=1"],
        "labeled_lambda": ["非负数", "负数"],
    }
    cases.append({
        "name": "break_continue_and_labeled_jumps",
        "summary": "Verify break/continue, labeled continue@loop & break@loop, and labeled lambda return@check.",
        "expected": expected_3,
        "actual": actual_3,
        "passed": actual_3 == expected_3,
    })

    # Case 4: Kotlin 2.2 non-local break/continue in inline lambda & return@forEach vs non-local return
    def inline_run(fn):
        return fn()

    nl_continue_out: list[str] = []
    for num in [1, None, 3, None, 5]:
        try:
            if num is None:
                def _on_null():
                    nl_continue_out.append("skip_null")
                    raise _ContinueOuter()
                inline_run(_on_null)
            val = num
            nl_continue_out.append(f"val={val}")
        except _ContinueOuter:
            continue

    nl_break_out: list[int] = []
    try:
        for num in [1, 2, 3, 4, 5]:
            def _check_break(n=num):
                if n == 4:
                    raise _BreakOuter()
            inline_run(_check_break)
            nl_break_out.append(num)
    except _BreakOuter:
        pass

    foreach_labeled: list[int] = []
    for item in [1, 2, 0, 4]:
        # return@forEach skips only current invocation
        if item == 0:
            continue
        foreach_labeled.append(item)

    foreach_nonlocal: list[int] = []
    try:
        for item in [1, 2, 0, 4]:
            if item == 0:
                raise _NonLocalReturn()
            foreach_nonlocal.append(item)
    except _NonLocalReturn:
        pass

    actual_4 = {
        "non_local_continue_2_2": nl_continue_out,
        "non_local_break_2_2": nl_break_out,
        "return_at_forEach": foreach_labeled,
        "non_local_return_exits_enclosing": foreach_nonlocal,
        "non_local_break_continue_stable": "2.2",
    }
    expected_4 = {
        "non_local_continue_2_2": ["val=1", "skip_null", "val=3", "skip_null", "val=5"],
        "non_local_break_2_2": [1, 2, 3],
        "return_at_forEach": [1, 2, 4],
        "non_local_return_exits_enclosing": [1, 2],
        "non_local_break_continue_stable": "2.2",
    }
    cases.append({
        "name": "non_local_jumps_and_return_at_foreach",
        "summary": "Verify Kotlin 2.2 non-local continue/break inside inline lambdas and return@forEach vs non-local return.",
        "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()
离线脚本确认区间/解构遍历、while 与 do-while 次数差异、loop@ 标签跳转、Kotlin 2.2 非局部 break/continue 及 return@forEach 语义全部通过。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a2132.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:Kotlin

课程关联工程包(登记关联43章) · 含当前章节或实例 · mbskycom202612a2132.zip

下载课程关联工程包:Kotlin

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2156.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

`forEach` 是内联函数,直接写 `return` 会触发非局部返回并立刻结束外层包含函数;而 `return@forEach` 仅结束当前这次 Lambda 调用,等价于跳过当前元素继续处理后续项。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习