operator 关键字在 Kotlin 中最典型的用途Kotlin 运算符重载,但它不仅仅用于此。它更广泛的作用是标记函数以支持特定的语言约定(Conventions),这些约定可以让你的代码以更 Kotlin 惯用的方式工作。
由于运算符重载已经做过详细的文档,这里不再介绍。主要介绍第二种用法,约定
其实和运算符重载一样,约定就是约定俗成。在运算符重载中,通过plus定义+这就是一种约定。但是还有另一种约定。
支持语言约定(Conventions)
委托属性(Delegated Properties):\ 通过operator fun getValue()和operator fun setValue(),你可以自定义属性的行为,如延迟初始化(lazy)、观察属性变化等。
class MyDelegate {
operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
return "Delegate says: ${property.name}"
}
}
class Example {
val delegated: String by MyDelegate()
}
// 使用
val example = Example()
println(example.delegated) // 调用 operator getValue更新: 2025-03-24 13:19:29
原文: https://www.yuque.com/dongpozhouzi-mshe3/zhm85g/sp7qcun878x4hrgw