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

运行离线 Python 校验:Kotlin 扩展静态分发、成员优先、可空接收者与成员扩展矩阵

PYTHONWindows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM/Gradle 工具链)。explore-extensions.py
explore-extensions.py231 行
"""Offline Kotlin 2.x semantic verifier for Chapter 22: Extensions."""
import json

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


class User:
    def __init__(self, name: str, secret: str = "hidden"):
        self.name = name
        self._secret = secret


def user_print_info(self: User) -> str:
    return f"用户名 {self.name}"


def list_swap(lst: list[int], i: int, j: int) -> list[int]:
    lst[i], lst[j] = lst[j], lst[i]
    return lst


def case_extension_fn_and_swap():
    u = User("Kotlin")
    info = user_print_info(u)
    nums = [1, 2, 3]
    list_swap(nums, 0, 2)
    # Extensions cannot access private members of the receiver class
    private_accessible = False
    actual = {"info": info, "swapped": nums, "private_accessible": private_accessible}
    expected = {"info": "用户名 Kotlin", "swapped": [3, 2, 1], "private_accessible": False}
    return {
        "name": "extension_fn_and_swap",
        "summary": "Verify User extension receiver access, MutableList.swap in-place swap, and private-member restriction",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_static_dispatch_and_member_wins():
    # Static dispatch: chosen by declared parameter type, not runtime subtype
    ext_table = {
        ("C", "foo"): lambda _self: "c",
        ("D", "foo"): lambda _self: "d",
    }

    def print_foo(obj_runtime_type: str, declared_type: str = "C") -> str:
        _ = obj_runtime_type
        return ext_table[(declared_type, "foo")](None)

    static_result = print_foo(obj_runtime_type="D", declared_type="C")

    # Member function always wins over an extension with identical signature
    members = {"foo": lambda: "成员函数"}
    extensions = {"foo": lambda: "扩展函数"}

    def resolve_call(name: str) -> str:
        if name in members:
            return members[name]()
        return extensions[name]()

    member_wins = resolve_call("foo")
    actual = {"static_dispatch_D_as_C": static_result, "member_vs_extension": member_wins}
    expected = {"static_dispatch_D_as_C": "c", "member_vs_extension": "成员函数"}
    return {
        "name": "static_dispatch_and_member_wins",
        "summary": "Verify static dispatch by declared type and member-over-extension priority",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_nullable_receiver_and_extension_properties():
    def any_nullable_describe(receiver) -> str:
        if receiver is None:
            return "空值"
        return f"非空:{receiver}"

    class Site:
        def __init__(self, name: str, url: str):
            self.name = name
            self.url = url

    def get_site_info(s: Site) -> str:
        return f"{s.name} ({s.url})"

    class KotlinStringBuilder:
        def __init__(self, text: str):
            self.chars = list(text)

        def to_string(self) -> str:
            return "".join(self.chars)

    def get_last_char(sb: KotlinStringBuilder) -> str:
        return sb.chars[-1]

    def set_last_char(sb: KotlinStringBuilder, ch: str) -> None:
        sb.chars[-1] = ch

    sb = KotlinStringBuilder("KOTLIN")
    before_last = get_last_char(sb)
    set_last_char(sb, "!")
    after_str = sb.to_string()

    # Extension properties have no backing field and cannot declare an initializer
    def validate_ext_prop(has_initializer: bool, has_getter: bool) -> str:
        if has_initializer:
            return "COMPILE_ERROR: Extension property cannot be initialized because it has no backing field"
        return "OK" if has_getter else "COMPILE_ERROR: Missing getter"

    actual = {
        "null_desc": any_nullable_describe(None),
        "non_null_desc": any_nullable_describe("KOTLIN"),
        "site_info": get_site_info(Site("蓝色天空", "mbsky.cn")),
        "before_last": before_last,
        "after_sb": after_str,
        "init_check": validate_ext_prop(True, False),
        "getter_check": validate_ext_prop(False, True),
    }
    expected = {
        "null_desc": "空值",
        "non_null_desc": "非空:KOTLIN",
        "site_info": "蓝色天空 (mbsky.cn)",
        "before_last": "N",
        "after_sb": "KOTLI!",
        "init_check": "COMPILE_ERROR: Extension property cannot be initialized because it has no backing field",
        "getter_check": "OK",
    }
    return {
        "name": "nullable_receiver_and_extension_properties",
        "summary": "Verify Any? nullable receiver, val/var extension properties, and no-backing-field rule",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_companion_import_and_member_extension():
    # Companion object extension
    class MyClass:
        pass

    companion_site_name = "蓝色天空"
    companion_created_is_myclass = isinstance(MyClass(), MyClass)

    # Package-scoped import visibility
    pkg_extensions = {"com.example.extensions.describe": lambda name, url: f"{name} -> {url}"}
    imported = {"com.example.extensions.describe"}
    import_ok = "com.example.extensions.describe" in imported
    imported_call = pkg_extensions["com.example.extensions.describe"]("蓝色天空", "mbsky.cn")

    # Member extensions: dispatch receiver (virtual) vs extension receiver (static)
    class D:
        def bar(self) -> str:
            return "D.bar"

    class D1(D):
        pass

    class C:
        def bar(self) -> str:
            return "C.bar"

        def baz(self) -> str:
            return "C.baz"

        def ext_foo_basic(self, d: D) -> str:
            return f"{d.bar()} / {self.baz()}"

        def ext_foo_conflict(self, d: D) -> str:
            # Extension receiver wins by default; this@C selects dispatch receiver
            return f"{d.bar()} / {self.bar()}"

        def ext_D_foo(self, _d: D) -> str:
            return "D.foo in C"

        def ext_D1_foo(self, _d: D1) -> str:
            return "D1.foo in C"

        def caller(self, d: D) -> str:
            # Declared type of parameter d is D -> statically binds to ext_D_foo, virtually dispatched on self
            return self.ext_D_foo(d)

    class C1(C):
        def ext_D_foo(self, _d: D) -> str:
            return "D.foo in C1"

        def ext_D1_foo(self, _d: D1) -> str:
            return "D1.foo in C1"

    actual = {
        "companion_name": companion_site_name,
        "companion_create": companion_created_is_myclass,
        "import_ok": import_ok,
        "imported_call": imported_call,
        "member_ext_basic": C().ext_foo_basic(D()),
        "member_ext_conflict": C().ext_foo_conflict(D()),
        "dispatch_matrix": [C().caller(D()), C1().caller(D()), C().caller(D1())],
    }
    expected = {
        "companion_name": "蓝色天空",
        "companion_create": True,
        "import_ok": True,
        "imported_call": "蓝色天空 -> mbsky.cn",
        "member_ext_basic": "D.bar / C.baz",
        "member_ext_conflict": "D.bar / C.bar",
        "dispatch_matrix": ["D.foo in C", "D.foo in C1", "D.foo in C"],
    }
    return {
        "name": "companion_import_and_member_extension",
        "summary": "Verify companion extensions, import scope, this@C disambiguation, and virtual-dispatch/static-extension matrix",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_extension_fn_and_swap(),
        case_static_dispatch_and_member_wins(),
        case_nullable_receiver_and_extension_properties(),
        case_companion_import_and_member_extension(),
    ]
    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-extensions-lab/explore-extensions.py

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

下载课程关联工程包:Kotlin

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

下载课程关联工程包:Kotlin

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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