前言
Java中常见操作符+ - * / ++ -- %等。Kotlin中允许对操作符进行重载,更加简洁实用的功能。
operator
重载操作符,用关键字operator。减操作符固定的函数名minus,加操作符函数名plus
fun test() {
val last = A(12.5f)
val to = A(21.5f)
val tem = to-last
println("tem:${tem.tem}")
}
data class A(var tem:Float){
operator fun minus(a:A):A{
return A(this.tem-a.tem)
}
}
输出:
tem:9.0
声明数据类A,主构造函数中声明了tem属性,在A内部使用了minus函数重载减操作符,让两个A对象进行相减
operator关键字和操作符重载对应函数名是固定的,不可更改- 重载函数参数和返回值可变,根据实际需求处理 类似于obj3 = obj1 - obj2
fun test() {
val temperature = 15.6f
val today = Weather(20.6f)
val temperatureInterval = today - temperature
println(temperatureInterval.temperature)
}
data class Weather(var temperature:Float){
operator fun minus(temperature:Float):Weather{
return Weather(this.temperature-temperature)
}
}
输出:
5.0
操作符重载是Kotlin语法糖
调用操作符()
fun normal(block:()->Unit){
block()
block.invoke()
}
高阶函数normal中函数类型参数调用,可用block(),也可用block.invoke()。操作符()在Kotlin中重载函数是invoke函数。
Functions.kt源码
public interface Function0<out R> : Function<R> {
public operator fun invoke(): R
}
public interface Function1<in P1, out R> : Function<R> {
public operator fun invoke(p1: P1): R
}
public interface Function2<in P1, in P2, out R> : Function<R> {
public operator fun invoke(p1: P1, p2: P2): R
}
上面重载operator函数类型的实例可以调用invoke的原因.
操作符和重载函数
一元操作符:
| 表达式 | 实际调用函数 |
|---|---|
| +a | a.unaryPlus() |
| -a | a.unaryMinus() |
| !a | a.not() |
递增和递减
| 表达式 | 实际调用函数 |
|---|---|
| a++ | a.inc() |
| a-- | a.dec() |
二元操作符
| 表达式 | 实际调用函数 |
|---|---|
| a+b | a.plus(b) |
| a-b | a.minus(b) |
| a*b | a.times(b) |
| a/b | a.div(b) |
| a%b | a.rem(b) |
| a..b | a.rangeTo(b) |
in操作符
| 表达式 | 实际调用函数 |
|---|---|
| a in b | b.constains(a) |
| a !in b | !b.constains(a) |
索引访问操作符
| 表达式 | 实际调用函数 |
|---|---|
| a[i] | a.get(i) |
| a[i,j] | a.get(i,j) |
| a[i_1,……,j_n] | a.get(i_1,……,i_n) |
| a[i]=b | a.set(i,b) |
| a[i,j]=b | a.set(i,j,b) |
| a[i_1,……,i_n]=b | a.set(i_1,……,i_n,b) |
总结
操作符重载是Kotlin语法糖,实现简洁实用的功能,访问操作符[]用list[i]获取集合里的元素。in操作符,使用for(value in list)遍历集合。+使协程上下文支持相加CoroutineScope(Dispatchers.Main+SupervisorJob())。