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

Kotlin 运算符重载

核对 Kotlin operator 关键字与可重载运算符全表、一元与自增自减规则、复合赋值 plus vs plusAssign 歧义、equals/compareTo 契约、索引 get/set 与 in/contains、invoke 对象可调用及二维向量与值类金额实践。

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

学完这一章,你能够

operator 约定、可重载全表与一元/自增规则

Kotlin 运算符重载遵循严格的**固定函数名约定**:通过在成员函数或扩展函数前添加 `operator` 关键字,将 `+`、`-`、`[]` 等符号语法在编译期直接翻译为对应函数调用(如 `a + b` 等价于 `a.plus(b)`,且不会改变运算符既定优先级)。除下表列出的 27 种表达式外,`&&`、`||`、`===`、`!==`、`is`、`!is`、`?:` 与 `=` 属于语言核心控制/身份语义,**不可重载**。

一元运算符对应无参函数 `unaryPlus`、`unaryMinus` 与 `not`。自增 `++` 与自减 `--` 对应 `inc()` 与 `dec()`,二者不接收参数且应返回计算后的新对象而不原地修改自身,编译器再把新值写回原变量,因此目标变量必须是 `var`。需说明的是:Kotlin 只需定义统一的 `inc()`(不像 C++ 以哑参数区分前后缀),但在表达式求值时,前缀 `++n` 返回递增后的新值,后缀 `n++` 先保存旧值作为表达式结果再将 `n.inc()` 写回变量。

复合赋值歧义、比较契约、索引/in 与 invoke

复合赋值 `a += b` 在编译期同时检查 `plus` 与 `plusAssign`:仅定义 `plus` 时翻译为 `a = a.plus(b)`(适用于不可变类型,要求 `a` 是 `var`);仅定义 `plusAssign`(返回 `Unit`)时翻译为原地修改 `a.plusAssign(b)`(适用于可变容器如 `Basket`,`a` 可声明为 `val`);若二者同时定义且目标为 `var`,编译器会因歧义直接报错。在比较运算方面,`==` 经由 `Any.equals` 解析(重写时只需 `override` 不可重复写 `operator`,且不能以扩展函数重载 `equals`),`<`/`>`/`<=`/`>=` 经由 `Comparable.compareTo` 解析,并应保持“当 `compareTo` 返回 `0` 时 `equals` 为 `true`”的契约。

方括号读取 `a[i]`、写入 `a[i] = v` 与包含判断 `x in a` 分别对应 `get`、`set` 与 `contains`(均支持多参数,可用于矩阵二维索引)。为类定义 `operator fun invoke(...)` 后,对象实例可直接像函数一样被调用(如 `Formatter` 同时重载单参 `invoke(text)` 与变长 `invoke(vararg texts)`)。

二维向量与金额实战、克制原则与常见问题

运算符重载最契合具有清晰代数语义的领域类型:例如二维 `Vector(x, y)` 实现 `+`、`-`、标量 `*`、取负 `-a` 及分量下标 `a[0]`/`a[1]`;以“分”为整数 `Long` 存储的 `@JvmInline value class Money(val cents: Long)` 既规避浮点精度误差,又能直观书写 `price * 3 + Money(500)` 得到 `64.97` 并比较大小。工程实践中切忌违背直觉滥用运算符(如用 `+` 做删除),且除 `equals` 外的运算符均可通过扩展函数补充。本站离线校验器已完整核对上述全部重载与实战运算。

Kotlin 可重载运算符与翻译函数全表

表达式翻译为说明
+aa.unaryPlus()一元正号
-aa.unaryMinus()一元负号
!aa.not()逻辑取反
a++a = a.inc()自增,要求 a 为 var(后缀表达式返回旧值,前缀返回新值)
a--a = a.dec()自减,要求 a 为 var
a + ba.plus(b)加法
a - ba.minus(b)减法
a * ba.times(b)乘法
a / ba.div(b)除法
a % ba.rem(b)取余
a..ba.rangeTo(b)闭区间
a..<ba.rangeUntil(b)左闭右开区间(Kotlin 1.9 稳定)
a in bb.contains(a)成员包含判断
a[i]a.get(i)索引读取
a[i] = ba.set(i, b)索引赋值
a()a.invoke()对象可调用语法
a == ba?.equals(b) ?: (b === null)结构相等(空安全翻译)
a != b!(a?.equals(b) ?: (b === null))结构不等
a > ba.compareTo(b) > 0大于比较
a < ba.compareTo(b) < 0小于比较
a >= ba.compareTo(b) >= 0大于等于比较
a <= ba.compareTo(b) <= 0小于等于比较
a += ba = a.plus(b) 或 a.plusAssign(b)复合加赋值,二者不可冲突共存
a -= ba = a.minus(b) 或 a.minusAssign(b)复合减赋值
a *= ba = a.times(b) 或 a.timesAssign(b)复合乘赋值
a /= ba = a.div(b) 或 a.divAssign(b)复合除赋值
a %= ba = a.rem(b) 或 a.remAssign(b)复合取余赋值

复合赋值 a += b 的解析规则

定义了什么a += b 的翻译适用场景
仅定义 plusa = a + b不可变类型,要求左侧变量 a 为 var
仅定义 plusAssigna.plusAssign(b)可变容器类型,左侧变量 a 可为 val
同时定义 plus 与 plusAssign编译报错(歧义)按类型是否可变二选一保留

运算符重载设计原则

原则说明
语义直观+ 表达相加/合并,* 表达缩放/重复,贴合普遍直觉
plus 不修改自身plus 等纯运算返回新对象;原地修改改用 plusAssign
避免同时定义 plus 与 plusAssign防止复合赋值语句产生编译歧义
compareTo 与 equals 一致compareTo 返回 0 时 equals 应同步返回 true
可读性优先若具名方法比符号更清晰,直接编写普通方法
不为省字符而重载重载的价值在于领域表达力而非减少敲键数

运行离线 Python 校验:Kotlin 运算符重载翻译、+= 歧义拦截、invoke 与向量/金额模型

python · 阅读源码
"""Offline Kotlin 2.x semantic verifier for Chapter 29: Operator Overloading."""
from dataclasses import dataclass
import json

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


@dataclass(frozen=True)
class Point:
    x: int
    y: int

    def __add__(self, other: "Point") -> "Point":
        return Point(self.x + other.x, self.y + other.y)

    def __str__(self) -> str:
        return f"({self.x}, {self.y})"


@dataclass(frozen=True)
class Counter:
    value: int

    def __neg__(self) -> "Counter":
        return Counter(-self.value)

    def inc(self) -> "Counter":
        return Counter(self.value + 1)

    def dec(self) -> "Counter":
        return Counter(self.value - 1)


def case_arithmetic_unary_and_inc_dec():
    a, b = Point(1, 2), Point(3, 4)
    c = Counter(10)
    neg_c = -c

    # Emulate Kotlin postfix n++ (returns old, binds n = n.inc()) and prefix ++n (binds then returns new)
    n = Counter(0)
    postfix_ret = n
    n = n.inc()
    after_inc = n
    n = n.dec()
    after_dec = n
    n = n.inc()
    prefix_ret = n

    non_overloadable = ["&&", "||", "===", "!==", "is", "!is", "?:", "="]
    actual = {
        "point_plus": str(a + b),
        "counter_neg": neg_c.value,
        "postfix_returned_old": postfix_ret.value,
        "after_inc": after_inc.value,
        "after_dec": after_dec.value,
        "prefix_returned_new": prefix_ret.value,
        "non_overloadable_count": len(non_overloadable),
    }
    expected = {
        "point_plus": "(4, 6)",
        "counter_neg": -10,
        "postfix_returned_old": 0,
        "after_inc": 1,
        "after_dec": 0,
        "prefix_returned_new": 1,
        "non_overloadable_count": 8,
    }
    return {
        "name": "arithmetic_unary_and_inc_dec",
        "summary": "Verify plus, unaryMinus, inc/dec expression values, and non-overloadable operator list",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_compound_assignment_and_ambiguity():
    def resolve_plus_assign(has_plus: bool, has_plus_assign: bool, target_is_var: bool) -> str:
        if has_plus and has_plus_assign:
            return "COMPILE_ERROR: Assignment operators ambiguity (both plus and plusAssign)"
        if has_plus_assign:
            return "CALL: a.plusAssign(b)"
        if has_plus:
            return "CALL: a = a.plus(b)" if target_is_var else "COMPILE_ERROR: Val cannot be reassigned"
        return "COMPILE_ERROR: No operator"

    basket = []
    for item in ("苹果", "香蕉", "书签"):
        basket.append(item)

    actual = {
        "plus_only_var": resolve_plus_assign(True, False, True),
        "plus_only_val": resolve_plus_assign(True, False, False),
        "plusAssign_only_val": resolve_plus_assign(False, True, False),
        "both_defined": resolve_plus_assign(True, True, True),
        "basket": basket,
    }
    expected = {
        "plus_only_var": "CALL: a = a.plus(b)",
        "plus_only_val": "COMPILE_ERROR: Val cannot be reassigned",
        "plusAssign_only_val": "CALL: a.plusAssign(b)",
        "both_defined": "COMPILE_ERROR: Assignment operators ambiguity (both plus and plusAssign)",
        "basket": ["苹果", "香蕉", "书签"],
    }
    return {
        "name": "compound_assignment_and_ambiguity",
        "summary": "Verify += resolution for plus vs plusAssign, val/var constraint, and ambiguity rejection",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_comparison_indexing_contains_invoke():
    @dataclass(frozen=True, order=True)
    class Version:
        major: int
        minor: int

    cur = Version(2, 2)
    old = Version(1, 9)

    class Playlist:
        def __init__(self):
            self._songs: list[str] = []

        def __iadd__(self, song: str):
            self._songs.append(song)
            return self

        def __getitem__(self, idx: int) -> str:
            return self._songs[idx]

        def __setitem__(self, idx: int, val: str) -> None:
            self._songs[idx] = val

        def __contains__(self, keyword: str) -> bool:
            return any(keyword in s for s in self._songs)

    pl = Playlist()
    pl += "Kotlin 基础"
    pl += "Kotlin 入门"
    pl += "Kotlin 实战"
    first_song = pl[0]
    pl[1] = "Kotlin 值类"

    class Formatter:
        def __init__(self, prefix: str):
            self.prefix = prefix

        def __call__(self, *texts: str) -> str:
            return ", ".join(f"{self.prefix}{t}" for t in texts)

    fmt = Formatter("[APP] ")

    actual = {
        "version_cmp": [cur > old, cur < old, cur >= Version(2, 2), cur == Version(2, 2), cur != old],
        "playlist_first": first_song,
        "playlist_updated": pl[1],
        "contains_checks": ["值类" in pl, "Java" in pl],
        "invoke_single": fmt("第一条"),
        "invoke_vararg": fmt("第一条", "第二条", "第三条"),
        "range_until_1_9": list(range(0, 3)),
    }
    expected = {
        "version_cmp": [True, False, True, True, True],
        "playlist_first": "Kotlin 基础",
        "playlist_updated": "Kotlin 值类",
        "contains_checks": [True, False],
        "invoke_single": "[APP] 第一条",
        "invoke_vararg": "[APP] 第一条, [APP] 第二条, [APP] 第三条",
        "range_until_1_9": [0, 1, 2],
    }
    return {
        "name": "comparison_indexing_contains_invoke",
        "summary": "Verify Comparable, get/set/contains (in), overloaded invoke, and ..< rangeUntil",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_vector_and_money_practical():
    @dataclass(frozen=True)
    class Vector:
        x: float
        y: float

        def __add__(self, o: "Vector") -> "Vector":
            return Vector(self.x + o.x, self.y + o.y)

        def __sub__(self, o: "Vector") -> "Vector":
            return Vector(self.x - o.x, self.y - o.y)

        def __mul__(self, s: float) -> "Vector":
            return Vector(self.x * s, self.y * s)

        def __neg__(self) -> "Vector":
            return Vector(-self.x, -self.y)

        def __getitem__(self, idx: int) -> float:
            if idx == 0:
                return self.x
            if idx == 1:
                return self.y
            raise IndexError(idx)

        def __str__(self) -> str:
            return f"({self.x}, {self.y})"

    @dataclass(frozen=True, order=True)
    class Money:
        cents: int

        def __add__(self, o: "Money") -> "Money":
            return Money(self.cents + o.cents)

        def __sub__(self, o: "Money") -> "Money":
            return Money(self.cents - o.cents)

        def __mul__(self, qty: int) -> "Money":
            return Money(self.cents * qty)

        def __str__(self) -> str:
            sign = "-" if self.cents < 0 else ""
            a = abs(self.cents)
            return f"{sign}{a // 100}.{a % 100:02d}"

    va, vb = Vector(1.0, 2.0), Vector(3.0, 4.0)
    price = Money(1999)
    total = price * 3 + Money(500)

    actual = {
        "vector_ops": [str(va + vb), str(va - vb), str(va * 2.0), str(-va), va[0], va[1]],
        "money_price": str(price),
        "money_total": str(total),
        "money_gt": total > price,
        "money_diff": str(total - price),
    }
    expected = {
        "vector_ops": ["(4.0, 6.0)", "(-2.0, -2.0)", "(2.0, 4.0)", "(-1.0, -2.0)", 1.0, 2.0],
        "money_price": "19.99",
        "money_total": "64.97",
        "money_gt": True,
        "money_diff": "44.98",
    }
    return {
        "name": "vector_and_money_practical",
        "summary": "Verify 2D Vector arithmetic/indexing and exact integer-cent Money value class operators",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_arithmetic_unary_and_inc_dec(),
        case_compound_assignment_and_ambiguity(),
        case_comparison_indexing_contains_invoke(),
        case_vector_and_money_practical(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对 Point 加法、Counter 自增自减、plus/plusAssign 歧义判定、Version/Playlist/Formatter 与 Vector/Money(cents) 精确计算。
运行离线 Python 校验:Kotlin 运算符重载翻译、+= 歧义拦截、invoke 与向量/金额模型

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

当前源码 SHA256:8dd9c40ecb85342b5ce9fd3ad713e371d372191c470b7afaa340e625d4d6b25f

下载本站示例源码

本地运行

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

下载Kotlin 运算符重载实验

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

ZIP SHA256:5b58899439df31a10ed812ef16ee133aaf08a4052831969d40966de7a2c92582

常见错误与边界

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

练习与解答

为什么对自定义类型同时定义 operator fun plus 和 operator fun plusAssign 会导致 a += b 报编译错误?重写 equals 时为何不能加 operator?

展开参考解答

当 a 为 var 且两个函数都匹配时,编译器无法决定应执行原地修改 a.plusAssign(b) 还是重绑定 a = a.plus(b),因而报歧义错误;equals 已在基类 Any 中声明为 operator,子类仅需 override。

规范与官方依据