操作符重载
-
Kotlin
允许我们为自己的类型提供预定义的一组操作符的实现。这些操作符具有固定的符号表示和固定的优先级。 -
通过调用自己代码中定义特定的函数名的函数,并且用
operator
修饰符标记。
// 一个简单的数据类
class Complex(var real: Double, var imaginary: Double) {
operator fun plus(other: Complex): Complex {
return Complex(real + other.real, imaginary + other.imaginary);
}
operator fun plus(other: Int):Complex {
return Complex(real + other,imaginary);
}
override fun toString(): String {
return "$real + ${imaginary}i";
}
}
fun main() {
// 使用的时候
val c1 = Complex(10.0, 20.0);
val c2 = Complex(30.0, 40.0);
// 直接用+运算符代替plus函数,事实上会调用plus函数
// this: 10 + 20i
// other: 30 + 40i
println(c1 + c2); // 40.0 + 60.0i
println(c1 + 5); // 15.0 + 20.0i
}
网友评论