kotlin运算符重载的范围
java是不支持任何运算符重载的,但是kotlin支持,这里要注意的是kotlin支持的运算符重载也是有限的,不像c++ 的重载那么强大灵活。
其中出镜率最高的几个,我们总结一下
==与equals , +与plus ,in与contains ,[]与get , >与compareto , ()与invoke
重载运算符的实例
定义一个复数类
//复数
class Complex(var real: Double, var image: Double) {
override fun toString(): String {
return "$real+${image}i"
}
}
然后我们对他进行一些运算符重载。
operator fun Complex.plus(other: Complex): Complex {
return Complex(this.real + other.real, this.image + other.image)
}
operator fun Complex.plus(other: Double): Complex {
return Complex(this.real + other, this.image)
}
operator fun Complex.plus(other: Int): Complex {
return Complex(this.real + other, this.image)
}
operator fun Complex.minus(real: Double): Complex {
return Complex(this.real - real, this.image)
}
//0 返回虚部 1实部
operator fun Complex.get(index:Int):Double{
return when(index){
0 -> this.real
1 -> this.image
else -> throw IndexOutOfBoundsException()
}
}
然后看看他的使用
fun main() {
val c = Complex(1.0, 2.0)
println(c)
val c1=Complex(3.0,4.0)
val c2=Complex(2.0,2.0)
println(c1+c2)
println(c1+3)
println(c1+2.0)
println(c1-1.0)
println(c1[1])
println(c1[0])
}
结果
通过这个例子 你应该能看出来,kotlin的运算符重载最大的作用就是增加这门语言的表达力
中缀表达式
看个最简单的例子,应该有人知道 to的作用吧。
那这个to 本质上是啥?
实际上他就等价于
println(2.to(3))
我们看一下源码:
这个infix 关键字 就是告诉编译器 可以 用 2 to 3 的这种简写方式了。
比如 我们想 逆序一个字符串
//index 为分割线 分割一个字符串
infix fun String.rotate(count: Int): String {
val index = count % length
return this.substring(index) + this.substring(0, index)
}
fun main() {
println("helloworld" rotate 5)
println("helloworld".rotate(5))
}
看下结果;
和 to的 写法 其实就是一样的了。 不加infix的话 就不可以用简写的方式了
中缀表达式 在 kotlin dsl中 很常见,一定要掌握。