Kotlin有个有趣的功能操作符重载(Operator overloading)。
先看一段程序:
val start = "Talk is cheap. "
val middle = "Show me the code. "
val end = "- android2me"
val result = start + middle + end
println(result)
输出结果:
Talk is cheap. Show me the code. - android2me
上面的例子我们发现这个加号(+)实现了字符串的连接。那么我们想想是这是怎么实现的。
我们点击加号,跳转到koltin的标准库的String文件中,光标停留在plus方法处。
下面是源代码:
package kotlin
/**
* The `String` class represents character strings. All string literals in Kotlin programs, such as `"abc"`, are
* implemented as instances of this class.
*/
public class String : Comparable<String>, CharSequence {
companion object {}
/**
* Returns a string obtained by concatenating this string with the string representation of the given [other] object.
*/
public operator fun plus(other: Any?): String
public override val length: Int
public override fun get(index: Int): Char
public override fun subSequence(startIndex: Int, endIndex: Int): CharSequence
public override fun compareTo(other: String): Int
}
从上面的分析看,加号(+)对应着plus这个方法。这个就是操作符重载,我们可以通过plus方法来定义“+”这个操作符。
一元操作符(Unary Operators)
操作符 | 方法名 |
---|---|
+a | a.unaryPlus() |
-a | a.unaryMinus() |
!a | a.not() |
a++ | a.inc() |
二元操作符(Binary Operators)
操作符 | 方法名 |
---|---|
a + b | a.plus(b) |
a – b | a.minus(b) |
a * b | a.times(b) |
a / b | a.div(b) |
a % b | a.mod(b) |
a..b | a.rangeTo(b) |
a in b | b.contains(a) |
a !in b | !b.contains(a) |
a += b | a.plusAssign(b) |
a -= b | a.minusAssign(b) |
a *= b | a.timesAssign(b) |
a /= b | a.divAssign(b) |
a %= b | a.modAssign(b) |
数值类型操作符(Array type operators)
操作符 | 方法名 |
---|---|
a[i] | a.get(i) |
a[i, j] | a.get(i, j) |
a[i_1, …, i_n] | a.get(i_1, …, i_n) |
a[i] = b | a.set(i, b) |
a[i, j] = b | a.set(i, j, b) |
a[i_1, …, i_n] = b | a.set(i_1, …, i_n, b) |
等于和不等于操作符(Equals Operation)
操作符 | 方法名 |
---|---|
a == b | a?.equals(b) ?: (b === null) |
a != b | !(a?.equals(b) ?: (b === null)) |
比较操作符(Comparison operators)
操作符 | 方法名 |
---|---|
a > b | a.compareTo(b) > 0 |
a < b | a.compareTo(b) < 0 |
a >= b | a.compareTo(b) >= 0 |
a <= b | a.compareTo(b) <= 0 |
调用操作符(Invoke operator)
操作符 | 方法名 |
---|---|
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) |
class Point(var x: Int, var y: Int) {
operator fun unaryMinus(): Point {
return Point(-x, -y)
}
override fun toString(): String {
return "[$x, $y]"
}
}
val point = Point(5, 8)
println(point)
println(-point)
打印输出:
I/System.out: [5, 8]
I/System.out: [-5, -8]
运用操作符重载给我们的开发带来了方便,但是要正确使用,防止产生歧义。
https://kotlinlang.org/docs/reference/operator-overloading.html
https://antonioleiva.com/operator-overload-kotlin/
https://www.programiz.com/kotlin-programming/operators