Kotlin 运算符重载

文章目录

运算符函数

我们平时使用的+-==[]等运算符其实是以函数(成员函数或扩展函数)的形式实现的。对应的符号有对应的函数名,并且需要以operator标记。

复制代码
operator fun 函数名()[: 返回值类型] [函数体]

运算符函数重载

我们可以将各种运算符重载为我们想要的操作。

例如,我们发现IntString并不能相加:

kt 复制代码
fun main() {
    print("Hello K" + 2)
}

我们可以重载plus运算符函数:

kt 复制代码
operator fun Int.plus(other: String) = "$this$other"


fun main() {
    print("Hello K" + 2)
}
复制代码
Hello K2

更多运算符说明可查看文档Operator overloading(英文)或运算符重载(中文)

Note:在 IDEA 中,将一个函数标记为operator,此函数如果为扩展函数,在写出接收者类型.之后就会提示可以重载的运算符名称,并且在后方会有该符号;如果为成员函数,则是在打出字母后会提示包含该字母的运算符及其符号。

相关推荐
pengyu11 小时前
【Kotlin 协程修仙录 · 渡劫境 · 中阶】 | 造化神兵:自定义 CoroutineDispatcher 与调度器的终极定制
android·kotlin
pengyu12 小时前
【Kotlin 协程修仙录 · 渡劫境 · 初阶】 | 飞升雷劫:CPS 变换与挂起函数字节码终极透视
android·kotlin
hunterandroid18 小时前
Android 多渠道打包与 Gradle 构建优化实战
android·前端·kotlin
pengyu19 小时前
【Kotlin 协程修仙录 · 大乘境 · 后阶】 | 死锁天劫:协程同步原语与 ThreadLocal 迁移之道
android·kotlin
天空之城--20 小时前
过去一周Android行业动态:编码技术与综合趋势精选
android·flutter·性能优化·kotlin·android jetpack
海兰2 天前
【 Python 量化交易】第10章:八大经典策略
android·python·kotlin
JMchen1232 天前
【Android 性能优化实战 60 讲】04 Memory Profiler 高阶玩法:深剖堆内存原理,实战定位 Kotlin 闭包隐式泄漏
android·性能优化·kotlin·实战·源码分析·内存泄漏·memory profiler
Kapaseker2 天前
我为什么喜欢 Compose ?
android·kotlin
limuyang22 天前
PDF Viewer KMP(基于 chrome 的 PDFium 内核)
android·kotlin
pengyu2 天前
【Kotlin 协程修仙录 · 大乘境 · 初阶】 | 跳出三界:协程在 KMP 与后端开发中的跨平台之道
android·kotlin