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

运行离线 Python 校验:Kotlin 空安全链式调用、Elvis 惰性求值、平台类型与 lateinit 生命周期

PYTHONWindows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM/Gradle 工具链)。explore-null-safety.py
explore-null-safety.py250 行
"""Offline Kotlin 2.x semantic verifier for Chapter 30: Null Safety."""
from dataclasses import dataclass
import json

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


def case_nullable_types_safe_call_and_elvis():
    @dataclass
    class Address:
        city: str
        zip_code: str | None

    @dataclass
    class User:
        name: str
        address: Address | None

    user = User("Kotlin", Address("北京", None))
    no_addr = User("Guest", None)

    safe_city = user.address.city if user.address is not None else None
    safe_missing_city = no_addr.address.city if no_addr.address is not None else None
    safe_zip_len = (
        len(user.address.zip_code)
        if user.address is not None and user.address.zip_code is not None
        else None
    )

    # Elvis ?: with lazy RHS (only evaluates RHS when LHS is None)
    rhs_eval_count = 0

    def parse_port(text: str | None) -> int:
        nonlocal rhs_eval_count
        parsed = int(text) if (text is not None and text.isdigit()) else None
        if parsed is None:
            rhs_eval_count += 1
            raise ValueError(f"端口不合法:{text}")
        return parsed

    def welcome(name: str | None) -> str:
        if name is None:
            return "名字不能为空"
        return f"欢迎 {name}"

    port_ok = parse_port("8080")
    port_err = None
    try:
        parse_port("abc")
    except ValueError as exc:
        port_err = str(exc)

    actual = {
        "safe_calls": [safe_city, safe_missing_city, safe_zip_len],
        "elvis_default": (None if True else "x") or "游客",
        "port_ok": port_ok,
        "port_err": port_err,
        "rhs_eval_count": rhs_eval_count,
        "welcome_results": [welcome("Kotlin"), welcome(None)],
    }
    expected = {
        "safe_calls": ["北京", None, None],
        "elvis_default": "游客",
        "port_ok": 8080,
        "port_err": "端口不合法:abc",
        "rhs_eval_count": 1,
        "welcome_results": ["欢迎 Kotlin", "名字不能为空"],
    }
    return {
        "name": "nullable_types_safe_call_and_elvis",
        "summary": "Verify chained safe calls (?.), lazy Elvis (?:) fallback, throw, and early return",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_not_null_assertion_let_and_safe_cast():
    def not_null_assert(v):
        if v is None:
            raise RuntimeError("java.lang.NullPointerException")
        return v

    ok_len = len(not_null_assert("KOTLIN"))
    npe_name = None
    try:
        not_null_assert(None)
    except RuntimeError as exc:
        npe_name = str(exc)

    let_outputs = []
    for email in ("dev@mbsky.cn", None):
        if email is not None:
            let_outputs.append(f"发送邮件到 {email}")

    def describe_safe_cast(val) -> str:
        t = val if isinstance(val, str) else None
        n = val if (isinstance(val, int) and not isinstance(val, bool)) else None
        return f"String={'null' if t is None else t}, Int={'null' if n is None else n}"

    def length_of(val) -> int:
        return len(val) if isinstance(val, str) else -1

    actual = {
        "bang_bang_ok": ok_len,
        "bang_bang_npe": npe_name,
        "let_outputs": let_outputs,
        "safe_casts": [describe_safe_cast("KOTLIN"), describe_safe_cast(42), describe_safe_cast(3.14)],
        "smart_cast_len": [length_of("Kotlin"), length_of(100)],
    }
    expected = {
        "bang_bang_ok": 6,
        "bang_bang_npe": "java.lang.NullPointerException",
        "let_outputs": ["发送邮件到 dev@mbsky.cn"],
        "safe_casts": [
            "String=KOTLIN, Int=null",
            "String=null, Int=42",
            "String=null, Int=null",
        ],
        "smart_cast_len": [6, -1],
    }
    return {
        "name": "not_null_assertion_let_and_safe_cast",
        "summary": "Verify !! NPE behavior, ?.let execution, as? safe cast, and is smart cast",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_platform_types_and_lateinit():
    # Emulate unannotated Java String! returning null
    java_val = None
    non_null_npe = None
    try:
        if java_val is None:
            raise RuntimeError("getName(...) must not be null")
    except RuntimeError as exc:
        non_null_npe = str(exc)

    safe_name = java_val if java_val is not None else "未命名"
    safe_len = len(java_val) if java_val is not None else 0

    class UserService:
        def __init__(self):
            self._sentinel = object()
            self._site_name = self._sentinel

        @property
        def is_initialized(self) -> bool:
            return self._site_name is not self._sentinel

        def get_site_name(self) -> str:
            if not self.is_initialized:
                raise RuntimeError("UninitializedPropertyAccessException: lateinit property siteName has not been initialized")
            return self._site_name  # type: ignore[return-value]

        def init(self, name: str) -> None:
            self._site_name = name

        def status_msg(self) -> str:
            return f"站点:{self.get_site_name()}" if self.is_initialized else "站点尚未初始化"

    svc = UserService()
    before_msg = svc.status_msg()
    uninit_err = None
    try:
        svc.get_site_name()
    except RuntimeError as exc:
        uninit_err = str(exc).split(":")[0]
    svc.init("mbsky.cn")
    after_msg = svc.status_msg()

    actual = {
        "platform_non_null_npe": non_null_npe,
        "platform_safe": [safe_name, safe_len],
        "lateinit_before": before_msg,
        "lateinit_uninit_exc": uninit_err,
        "lateinit_after": after_msg,
    }
    expected = {
        "platform_non_null_npe": "getName(...) must not be null",
        "platform_safe": ["未命名", 0],
        "lateinit_before": "站点尚未初始化",
        "lateinit_uninit_exc": "UninitializedPropertyAccessException",
        "lateinit_after": "站点:mbsky.cn",
    }
    return {
        "name": "platform_types_and_lateinit",
        "summary": "Verify Java String! platform type runtime check and lateinit isInitialized/exception lifecycle",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_collections_nullability_and_safe_apis():
    names = ["Alpha", "Beta"]
    maybe_names = None
    names_with_null = ["Alpha", None, "Beta"]
    scores = {"Alpha": 90}

    cleaned = [x for x in names_with_null if x is not None]
    get_or_null = names[10] if 10 < len(names) else None
    first_or_null = next(iter([]), None)

    actual = {
        "names_size": len(names),
        "maybe_names_size": len(maybe_names) if maybe_names is not None else None,
        "with_null_size": len(names_with_null),
        "with_null_idx1": names_with_null[1],
        "map_missing": scores.get("Beta"),
        "map_missing_elvis": scores.get("Beta") if scores.get("Beta") is not None else 0,
        "filter_not_null": cleaned,
        "get_or_null_oob": get_or_null,
        "first_or_null_empty": first_or_null,
    }
    expected = {
        "names_size": 2,
        "maybe_names_size": None,
        "with_null_size": 3,
        "with_null_idx1": None,
        "map_missing": None,
        "map_missing_elvis": 0,
        "filter_not_null": ["Alpha", "Beta"],
        "get_or_null_oob": None,
        "first_or_null_empty": None,
    }
    return {
        "name": "collections_nullability_and_safe_apis",
        "summary": "Verify List<T> vs List<T?> vs List<T>?, Map nullable lookup, filterNotNull, and *OrNull APIs",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_nullable_types_safe_call_and_elvis(),
        case_not_null_assertion_let_and_safe_cast(),
        case_platform_types_and_lateinit(),
        case_collections_nullability_and_safe_apis(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM/Gradle 工具链)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

入口文件:projects/kotlin-null-safety-lab/explore-null-safety.py

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

下载课程关联工程包:Kotlin

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

下载课程关联工程包:Kotlin

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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