在 Kotlin 中使用运算符时,会调用其对应的成员函数。例如,表达式 a+b
在底层会被转换为 a.plus(b)
。
fun main(args: Array<String>) {
val a = 5
val b = 10
print(a.plus(b)) // print(a+b)
}
运行程序后,输出将是
15
实际上,plus()
函数被重载以支持各种 Kotlin 基本类型和 String
。
// + operator for basic types operator fun plus(other: Byte): Int operator fun plus(other: Short): Int operator fun plus(other: Int): Int operator fun plus(other: Long): Long operator fun plus(other: Float): Float operator fun plus(other: Double): Double // for string concatenation operator fun String?.plus(other: Any?): String
您还可以通过重载相应的函数来定义运算符如何作用于对象。例如,您需要通过重载 plus()
函数来定义 +
运算符如何作用于对象。
示例:重载 + 运算符
fun main(args: Array<String>) {
val p1 = Point(3, -8)
val p2 = Point(2, 9)
var sum = Point()
sum = p1 + p2
println("sum = (${sum.x}, ${sum.y})")
}
class Point(val x: Int = 0, val y: Int = 10) {
// overloading plus function
operator fun plus(p: Point) : Point {
return Point(x + p.x, y + p.y)
}
}
运行程序后,输出将是
sum = (5, 1)
在此,plus()
函数被标记为 operator
关键字,以告知编译器正在重载 +
运算符。
表达式 p1 + p2
在底层会被转换为 p1.plus(p2)
。
示例:-- 运算符重载
在本例中,您将学习如何重载 --
运算符。表达式 --a
在底层会被转换为 a.dec()
。
dec()
成员函数不接受任何参数。
fun main(args: Array<String>) {
var point = Point(3, -8)
--point
println("point = (${point.x}, ${point.y})")
}
class Point(var x: Int = 0, var y: Int = 10) {
operator fun dec() = Point(--x, --y)
}
运行程序后,输出将是
point = (2, -9)
请记住:
operator fun dec() = Point(--x, --y)
等同于
operator fun dec(): Point { return Point(--x, --y) }
一些要点
1. 重载运算符时,应尽量保持运算符的原始含义。例如,
fun main(args: Array<String>) {
val p1 = Point(3, -8)
val p2 = Point(2, 9)
var sum = Point()
sum = p1 + p2
println("sum = (${sum.x}, ${sum.y})")
}
class Point(val x: Int = 0, val y: Int = 10) {
// overloading plus function
operator fun plus(p: Point) = Point(x - p.x, y - p.y)
}
虽然上面的程序在技术上是正确的,但我们使用 +
运算符来减去对象的相应属性,这使得程序令人困惑。
2. 与 Scala 等语言不同,Kotlin 只能重载一组特定的 运算符。请访问此页面了解 Kotlin 中可以重载的运算符及其对应的成员函数。