Kotlin 操作符重载

Kotlin 的‌操作符重载 ‌机制允许开发者通过预定义函数名和 operator 修饰符,为自定义类型赋予与内置类型相似的操作符行为。以下是核心要点和示例:


一、操作符重载的实现方式

  1. 成员函数重载

    在类内部声明特定名称的成员函数并标记 operator

    kotlin 复制代码
    data class Point(val x: Int, val y: Int) {
        operator fun plus(other: Point) = Point(x + other.x, y + other.y)  // + 操作符 ‌:ml-citation{ref="2,4" data="citationList"}
    }
    val p1 = Point(1, 2)
    val p2 = Point(3, 4)
    println(p1 + p2)  // 输出: Point(x=4, y=6)
  2. 扩展函数重载

    为现有类添加操作符行为(无需修改原类):

    kotlin 复制代码
    operator fun Point.minus(other: Point) = Point(x - other.x, y - other.y)  // - 操作符 ‌:ml-citation{ref="4,7" data="citationList"}
    println(p2 - p1)  // 输出: Point(x=2, y=2)

二、常见操作符与对应函数

操作符类型 操作符示例 对应函数名 说明
算术操作符 +, -, * plus, minus, times 优先级遵循数学规则(如 * 优先于 +)‌34
比较操作符 ==, >, < equals, compareTo == 调用 equals>< 依赖 compareTo ‌68
索引操作符 [], []= get, set 允许类似数组的访问和修改 ‌34
调用操作符 () invoke 使对象可像函数一样调用 ‌37
一元操作符 +a, -a, ! unaryPlus, unaryMinus, not 作用于单操作数 ‌16

三、示例与应用场景

1. 自定义向量运算

kotlin 复制代码
data class Vector(val x: Int, val y: Int) {
    operator fun times(scalar: Int) = Vector(x * scalar, y * scalar)  // * 操作符 ‌:ml-citation{ref="2,4" data="citationList"}
}
val v = Vector(2, 3)
println(v * 5)  // 输出: Vector(x=10, y=15)

2. 集合扩展操作

kotlin 复制代码
operator fun List<Int>.get(indexes: IntRange): List<Int> {  // 重载 [] 支持范围索引 ‌:ml-citation{ref="3,7" data="citationList"}
    return this.slice(indexes)
}
val list = listOf(1, 2, 3, 4, 5)
println(list[1..3])  // 输出: [2, 3, 4]

3. 自定义比较逻辑

kotlin 复制代码
class Student(val score: Int) {
    operator fun compareTo(other: Student) = score.compareTo(other.score)  // > 和 < 操作符 ‌:ml-citation{ref="6,8" data="citationList"}
}
val s1 = Student(85)
val s2 = Student(90)
println(s1 < s2)  // 输出: true

四、注意事项

  1. 函数签名必须匹配
    操作符函数的参数和返回类型需严格符合约定(如 plus 需返回新对象)‌14。
  2. 避免滥用
    过度重载可能降低代码可读性(如用 + 表示非加法操作)‌26。
  3. 不可修改原对象
    一元操作符(如 inc())应返回新实例,而非修改原对象 ‌68。

五、与 Java 的对比

特性 Kotlin 操作符重载 Java 实现方式
语法简洁性 通过 operator 关键字直接支持 需手动实现特定方法(如 add 方法)
扩展性 支持扩展函数重载 仅能通过类内部方法重载
操作符范围 覆盖更广(如 invoke 有限支持(如 + 仅限字符串拼接)

通过合理使用操作符重载,可显著提升代码表达力,但需遵循语义明确的原则

相关推荐
2501_915921435 分钟前
混合开发应用安全方案,在多技术栈融合下构建可持续、可回滚的保护体系
android·安全·ios·小程序·uni-app·iphone·webview
AllBlue27 分钟前
unity嵌入安卓界面,如何显示状态
android·unity·游戏引擎
QuantumLeap丶1 小时前
《Flutter全栈开发实战指南:从零到高级》- 21 -响应式设计与适配
android·javascript·flutter·ios·前端框架
用户69371750013841 小时前
24.Kotlin 继承:调用超类实现 (super)
android·后端·kotlin
00后程序员张2 小时前
Fastlane 结合 开心上架,构建跨平台可发布的 iOS 自动化流水线实践
android·运维·ios·小程序·uni-app·自动化·iphone
游戏开发爱好者82 小时前
iOS 性能测试的工程化方法,构建从底层诊断到真机监控的多工具测试体系
android·ios·小程序·https·uni-app·iphone·webview
帅得不敢出门2 小时前
Android11~13 Framework实现Ntp服务器多域名轮询同步时间
android·服务器·python·framework·github
2501_916008893 小时前
iOS App 混淆的真实世界指南,从构建到成品 IPA 的安全链路重塑
android·安全·ios·小程序·uni-app·cocoa·iphone
百锦再3 小时前
.NET到Java的终极迁移指南:最快转型路线图
android·java·开发语言·python·rust·go·.net