kotlin关键字operator

一. 概念

在Kotlin中,operator是一个关键字,用于声明一些运算符函数。这些运算符函数是用来对操作符进行操作的,例如+、-、*、/等等

讲起来还是比较晦涩,直接上示例

二. 示例

普通函数:

class PointNormal(val value : Int) {
    // 只是一个普通的函数
    fun plus(otherPoint: PointNormal) : PointNormal {
        return PointNormal(value + otherPoint.value)
    }
}
// 示例: 跟普通函数使用
val pointNormal = PointNormal(1).plus(PointNormal(2))

使用之后的示例: 方法前添加操作符operator

class Point(val value: Int) {
    // 方法前添加操作符operator
    operator fun plus(otherPoint: Point) :Point {
        return Point(value + otherPoint.value)
    }
}
// 使用了操作符operator重载了加号的运算符,可以直接使用+号调用
val point = Point(1) + Point(2)

三. 源码示例

在Kotlin中,我们可以通过使用operator关键字来重载下标运算符[],也可以通过使用operator关键字和set函数来重载下标运算符的赋值操作[]=。例如,我们可以如下所示来重载[][]=运算符:

public class Array<T> {
   
    public operator fun get(index: Int): T

    public operator fun set(index: Int, value: T): Unit

	/**省略了其它的方法*/
    ...
}

使用示例

fun main() {
    val myList = arrayOf<Int>()
    myList[0] = 1 // 调用set方法
    println(myList[0]) // 调用get方法,输出1
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值