蓝色天空网mbsky.com · 知识 · 实践 · 创造Kotlin · 本地阅读预览
教程 / 移动开发 / Kotlin

Kotlin 扩展

系统核对 Kotlin 扩展函数与扩展属性的静态解析机制、成员函数优先原则、可空接收者、伴生对象扩展、跨包导入作用域以及类内部成员扩展的分发/扩展双接收者规则。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

扩展函数定义、接收者 this 与封装边界

Kotlin 支持在不修改目标类源码、也不引入继承或装饰器包装的前提下,为既有类型补充新函数与属性,使调用处呈现与成员访问一致的流畅点号语法。声明扩展函数时在函数名前添加接收者类型与点号(如 `fun User.printInfo()` 或 `fun MutableList<Int>.swap(index1: Int, index2: Int)`),函数体中的 `this` 绑定到调用点左侧的接收者对象(对 `[1, 2, 3]` 执行 `swap(0, 2)` 得到 `[3, 2, 1]`)。从编译原理看,扩展并不会真正修改接收者类的字节码结构,而是生成以接收者作为首参的静态工具函数,因此扩展函数无法访问被扩展类的 `private` 或 `protected` 成员。

静态解析机制、成员优先与可空接收者

由于扩展并非虚方法,具体调用哪个扩展函数完全由变量在调用处的**静态声明类型**决定,而不参与运行时多态:若 `D` 继承自 `C` 且两者各自定义了 `foo()` 扩展,形参类型为 `c: C` 的 `printFoo(D())` 仍会固定绑定并输出 `c`。同时,当类自身存在与扩展函数签名完全相同的成员函数时,**成员函数永远胜出**;给第三方库编写扩展时需警惕上游未来新增同名成员导致扩展静默失效的风险。

扩展函数的接收者类型允许标注为可空类型(例如 `fun Any?.describe(): String`),使得 `null` 值也能直接调用该扩展而不会触发空指针异常;在函数体内部通过 `if (this == null)` 分支判空后,编译器会自动将后续路径中的 `this` 智能转换为非空类型(如对 `null` 返回 `空值`,对非空字符串返回 `非空:...`)。本站离线语义校验器已核对静态分发、成员优先以及可空接收者三条规则。

扩展属性、伴生对象扩展与跨包导入

扩展属性通过在属性名前指定接收者类型声明(例如只读 `val Site.info` 或可变 `var StringBuilder.lastChar`)。因为扩展不会向目标类插入真实存储字段,扩展属性**不存在 backing field(幕后字段)**,既禁止编写直接初始化器(如 `val Foo.bar = 1` 编译报错),也无法缓存计算结果,必须显式提供 `get()`(`var` 还须提供 `set(value)`),且只能声明在顶层或类内部,不能声明在函数体内。

若类定义了伴生对象,可对其声明扩展函数与扩展属性(如 `fun MyClass.Companion.create()` 与 `val MyClass.Companion.siteName`;若伴生对象具名则替换 `Companion` 为该名称),调用方即可通过 `类名.成员` 以静态风格访问。顶层扩展归属所在包,跨包使用时必须显式 `import` 具体扩展名或整包导入;不同包内允许存在同名扩展而互不冲突。

成员扩展的双接收者与多态分发矩阵

扩展也可以定义在另一个类内部(成员扩展),此时同时具备两个隐式接收者:外围定义类实例称为**分发接收者(dispatch receiver)**,被扩展类实例称为**扩展接收者(extension receiver)**。当两者拥有同名成员(如 `C.bar()` 与 `D.bar()`)时,未限定调用优先解析扩展接收者成员,需访问外围分发接收者成员时必须使用限定语法 `this@C.bar()`。此外,成员扩展可标记为 `open` 并在子类中 `override`,调用时对分发接收者执行**虚拟动态分发**(`C1().caller(D())` 调用 `C1` 的重写版本),而对扩展接收者依旧执行**静态分发**(`C().caller(D1())` 仍按形参类型 `D` 调用 `D.foo in C`)。离线校验器已完整核对上述组合矩阵。

Kotlin 扩展常见问题速查

问题原因解决办法
给子类对象调用扩展,结果执行了父类的扩展扩展函数在编译期按静态声明类型解析,不参与动态多态将参数声明类型细化为子类,或改用类的成员函数重写
自定义扩展被类内同名同参成员方法覆盖成员函数优先级永远高于同签名扩展函数调整扩展函数命名或参数签名,或改用作用域函数辅助
扩展属性编写初始化器触发编译错误扩展属性不具备幕后字段(backing field)改为显式实现 getter(可变属性同步实现 setter)
在扩展函数内部尝试访问目标类私有成员失败扩展在字节码层面位于目标类外部,无权破坏封装通过目标类公开 API 访问,或将成员扩展定义在同类内部
跨包文件无法识别已定义的扩展函数扩展仅在定义包或显式导入的作用域内可见使用 import 导入该扩展函数或对应包
成员扩展内部出现同名成员冲突同时存在分发接收者与扩展接收者,默认扩展接收者优先使用 this@外部类名 显式指向分发接收者

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

python · 阅读源码
"""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()
预期结果 · 待实际运行核验
  • 核对 MutableList.swap=[3,2,1]、printFoo(D()) 输出 c、成员函数优先于扩展、扩展属性无 backing field 以及分发接收者虚拟/扩展接收者静态矩阵。
运行离线 Python 校验:Kotlin 扩展静态分发、成员优先、可空接收者与成员扩展矩阵

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

当前源码 SHA256:d4a026aa54885e6d6a7056ce28f699924151cd6a7a9ec2991eee82b23c72bd45

下载本站示例源码

本地运行

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

下载Kotlin 扩展实验

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

ZIP SHA256:8be01b2c8c48f645f26109f835b5e579b517c5b0858673b058b94699808a6e1c

常见错误与边界

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

练习与解答

为什么对声明类型为父类 C、运行时类型为子类 D 的变量调用扩展函数 foo() 时会执行 C.foo()?扩展属性为何不能写初始化器?

展开参考解答

扩展函数本质上编译为静态方法,在编译期依据接收者的静态声明类型绑定而不走虚方法表;扩展属性不会向目标类添加真实字段(无 backing field),因此无法保存初始值,必须显式编写 getter/setter。

规范与官方依据