首先申明下,本文为笔者学习《Kotlin 程序开发入门精要》的笔记,并加入笔者自己的理解和归纳总结。
Kotlin允许我们对数据类型的一组预定义的操作符提供实现函数。
表达式 | 对应的函数 |
---|---|
+a | a.unaryPlus() |
-a | a.unaryMinus() |
!a | a.not() |
a++ | a.inc() |
a– | a.dec() |
我们假设一个复数类Complex
,有实部real
和虚部imag
class Complex(r: Int, i: Int) {
var real = r
var imag = i
override fun toString(): String {
if (imag >= 0) {
return "$real +${imag}i"
} else {
return "$real ${imag}i"
}
}
}
函数重载inc()
和dec()
operator fun Complex.inc() = Complex(real + 1, imag + 1)
operator fun Complex.dec() = Complex(real - 1, imag - 1)
fun main(args: Array) {
var comp1 = Complex(5, -10)
println(comp1++) // 5 -10i
println(++comp1) // 7 -8i
}
表达式 | 对应的函数 |
---|---|
a + b | a.plus(b) |
a - b | a.minus(b) |
a * b | a.times(b) |
a / b | a.div(b) |
a % b | a.mod(b) |
a…b | a.rangeTo(b) |
a in b | b.contains(a) |
a !in b | !b.contains(a) |
函数重载plus()
和minus()
operator fun Complex.plus(other: Complex) = Complex(real + other.real, imag + other.imag)
operator fun Complex.minus(other: Complex) = Complex(real - other.real, imag - other.imag)
fun main(args: Array) {
var comp1 = Complex(8, -10)
var comp2 = Complex(5, 5)
println(comp1 + comp2) // 13 -5i
println(comp1 - comp2) // 3 -15i
}
表达式 | 对应的函数 |
---|---|
a[i] | a.get(i) |
a[i, j] | a.get(i, j) |
a[i] = b | a.set(i, b) |
a[i, j] = b | a.set(i, j, b) |
函数重载get()
和set()
方法
class StringList {
var list = mutableListOf("Hello World!", "Welcome")
operator fun get(i: Int): String {
return list[i]
}
operator fun set(i: Int, value: String) {
list[i] = value
}
operator fun get(i: Int, j: Int): Char {
return list[i][j]
}
}
fun main(args: Array) {
var list = StringList()
println(list[0]) // Hello World!
println(list[1, 5]) // m
list[0] = "Hi Mike"
println(list[0]) // Hi Mike
}
表达式 | 对应的函数 |
---|---|
a+=b | a.plusAssign(b) |
a-=b | a.minusAssign(b) |
a*=b | a.timesAssign(b) |
a/=b | a.divAssign(b) |
a%=b | a.modAssign(b) |
函数重载timesAssign()
方法
operator fun Complex.timesAssign(n: Int) {
real *= n
imag *= n
}
fun main(args: Array) {
var comp = Complex(5, -10)
comp *= 5
println(comp) // 25 -50i
}
表达式 | 对应的函数 |
---|---|
a>b | a.compareTo(b)>0 |
a | a.compareTo(b)<0 |
a>=b | a.compareTo(b)>=0 |
a<=b | a.compareTo(b)<=0 |
a==b | a?.equals(b) ?: b===null |
a!=b | !(a?.equals(b) ?: b===null) |
函数重载equals()
方法,必须在Complex
内部实现
operator override fun equals(other: Any?): Boolean {
if (other is Complex) {
return real == other.real && imag == other.imag
}
return false
}
函数重载compareTo()
方法
operator fun Complex.compareTo(other: Complex): Int {
var diff = real - other.real
return if (diff != 0) diff else imag - other.imag
}
fun main(args: Array) {
var comp1 = Complex(5, 10)
var comp2 = Complex(8, -6)
var comp3 = Complex(8, -6)
println(comp1 > comp2) // false
println(comp2 <= comp3) // true
println(comp1 == comp2) // false
println(comp2 == comp3) // true
}