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
}

猜你喜欢

转载自blog.csdn.net/flytosky21/article/details/129944237
今日推荐