蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线校验 if 表达式、when 智能转换、穷尽性及 Kotlin 2.2 守卫条件

PYTHONWindows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM Kotlin 工具链)。explore-condition-control.py
explore-condition-control.py243 行
"""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()
本例需在 Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM Kotlin 工具链)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM Kotlin 工具链)。

入口文件:projects/kotlin-condition-control-lab/explore-condition-control.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-condition-control.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM Kotlin 工具链)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Kotlin

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

下载课程关联工程包:Kotlin

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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