1.什么是infix函数
Kotlin允许在不使用括号和点号的情况下调用函数,那么这种函数被称为 infix函数。
例如:集合的to就是一个infix函数。看起来像是一个关键字,实际是一个to()方法。
map(
1 to "one",
2 to "two",
3 to "three"
)
下面是to的源码,可以发现to() 方法就有用infix修饰
/**
* Creates a tuple of type [Pair] from this and [that].
*
* This can be useful for creating [Map] literals with less noise, for example:
* @sample samples.collections.Maps.Instantiation.mapFromPairs
*/
public infix fun <A, B> A.to(that: B): Pair<A, B> = Pair(this, that)
中缀表示法
中缀表示法(或中缀记法)是一个通用的算术或逻辑公式表示方法, 操作符是以中缀形式处于操作数的中间(例:3 + 4 中的 + )。
标有infix函数,可以使用中缀表示法调用
2.infix 函数的定义
需要满足的条件:
- 必须是成员函数或扩展函数
- 必须只有一个参数
- 其参数不得接受可变数量的参数且不能有默认值
class Util(val number:Int) {
infix fun sum(other: Int) {
println(number + other)
}
}
fun main(){
val u = Util(5)
u sum 5 // 10
u sum 7 // 12
}