16. 运算符
2017-11-14 本文已影响98人
厚土火焱
kotlin支持的运算符 +, -, *, /, %,=,+=, -=, *=, /=, %=, ++, --, &&, ||, !, ==, !=, ===, !==, <, >, <=, >=, ... 详情参考kotlin网站
运算符本质上是一个函数。
kotlin的运算符可以重载
比如我们可以给 “+” 增加更多的计算能力
建一个复数类,然后增加多个计算方法
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)
}
operator fun plus(other: Any): Any{
return "$real + ${imaginary}i" + "+" + other.toString()
}
override fun toString(): String {
return "$real + ${imaginary}i"
}
}
这样,就可以用 + 来实现复数和整数相加,以及复数和任意其他类型相加了。和整数相加,我们只对 real 进行计算,然后把 imaginary 部分保持不变。任意其他类型,我们用 String 类型来做例子。把原复数给出再加上后要相加的字符串。
fun main(args: Array<String>) {
var c1 = Complex(3.0, 4.0)
var c2 = Complex(5.3, 9.8)
println("($c1) + ($c2) = " + (c1 + c2))
println(c2 + 5)
println(c1 + "这是奇怪的加法")
}
这些加法的输出是
(3.0 + 4.0i) + (5.3 + 9.8i) = 8.3 + 13.8i
10.3 + 9.8i
3.0 + 4.0i+这是奇怪的加法