java是不支持任何运算符重载的,可是kotlin支持,这里要注意的是kotlin支持的运算符重载也是有限的,不像c++ 的重载那么强大灵活。html
其中出镜率最高的几个,咱们总结一下c++
==与equals , +与plus ,in与contains ,[]与get , >与compareto , ()与invoke安全
定义一个复数类bash
//复数
class Complex(var real: Double, var image: Double) {
override fun toString(): String {
return "$real+${image}i"
}
}
复制代码
而后咱们对他进行一些运算符重载。ide
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()
}
}
复制代码
而后看看他的使用ui
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])
}
复制代码
结果this
经过这个例子 你应该能看出来,kotlin的运算符重载最大的做用就是增长这门语言的表达力spa
看个最简单的例子,应该有人知道 to的做用吧。 3d
那这个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中 很常见,必定要掌握。