operator 将一个函数标记为重载一个操作符或者实现一个约定

表达式 翻译为
+a a.unaryPlus()
-a a.unaryMinus()
!a a.not()
a + b a.plus(b)
a - b a.minus(b)
a * b a.times(b)
a / b a.div(b)
a % b a.rem(b)、 a.mod(b) (已弃用)
a..b a.rangeTo(b)
a in b b.contains(a)
a !in b !b.contains(a)
a == b a?.equals(b) ?: (b === null)
a != b !(a?.equals(b) ?: (b === null))
a > b a.compareTo(b) > 0
a < b a.compareTo(b) < 0
a >= b a.compareTo(b) >= 0
a <= b a.compareTo(b) <= 0
a() a.invoke()
a(i) a.invoke(i)
a(i, j) a.invoke(i, j)
a(i_1, ……, i_n) a.invoke(i_1, ……, i_n)

unaryMinus

data class Point(val x: Int, val y: Int)

operator fun Point.unaryMinus() = Point(-x, -y)

val point = Point(10, 20)

fun main() {
   println(-point)  // 输出“Point(x=-10, y=-20)”
}

plus

data class Counter(val dayIndex: Int) {
    operator fun plus(increment: Int): Counter {
        return Counter(dayIndex + increment)
    }
}

invoke

class Hello{
    operator fun invoke(target: String) {
        say()
        println(target)
    }

    fun say() {
        println("hello ")
    }
}

fun main() {
    val hello = Hello()
    hello("world")
}

你可能感兴趣的:(operator 将一个函数标记为重载一个操作符或者实现一个约定)