在 Kotlin 里,中缀函数属于一种特殊的函数,它能以中缀表示法来调用,也就是把函数名置于两个操作数之间。
特性:
- 仅适用于成员函数或扩展函数:中缀函数既可以是类的成员函数,也可以是对某个类的扩展函数。
- 仅有一个参数:中缀函数只能有一个参数,并且不能有默认值。
- 使用 infix 关键字:要把一个函数定义成中缀函数,必须使用 infix 关键字。
语法:
// 成员函数
class MyClass {
infix fun functionName(param: Type): ReturnType {
// 函数体
}
}
// 扩展函数
infix fun Type.functionName(param: Type): ReturnType {
// 函数体
}
使用示例:
class Person(val name: String) {
// 定义一个中缀函数
infix fun knows(other: Person): Boolean {
return name == other.name
}
}
fun main() {
val person1 = Person("Alice")
val person2 = Person("Bob")
val person3 = Person("Alice")
// 使用中缀表示法调用函数
val result1 = person1 knows person2
val result2 = person1 knows person3
println(result1) // 输出: false
println(result2) // 输出: true
}
在这个例子中,knows 是 Person 类的中缀函数,用于判断两个 Person 对象是否代表同一个人。在 main 函数里,我们使用中缀表示法调用 knows 函数,就像使用运算符一样。
运算符优先级:
- 结果上相等(== 等价于 equals())
- 引用上相等(=== 判断两个变量是否都是引用同一个对象)
优先级 | 运算符 |
---|---|
最高 | 后置:++ . ? |
前置:+ ++ ! | |
类型转换:as | |
乘除余:* / % | |
加减:+ - | |
范围运算符:.. | |
Infix function 中缀函数 | |
Elvis 运算符:?: | |
in !in is !is | |
< > <= >= | |
== != === !== | |
逻辑与:&& | |
逻辑或: || | |
最低 | 赋值: = += -= *= /= %= |
1 shl 2 + 3
相当于1 shl (2+3)
0 until n*2
相当于0 until (n*2)
xs union ys as Set<*>
相当于xs union (ys as Set<*>)
a && b xor c
相当于a && (b xor c)
a xor b in c
相当于(a xor b) in c
如果需要在类中使用中缀函数,必须明确函数的调用方(接收器), 如:
class Person(val name: String) {
// 定义一个中缀函数
infix fun knows(other: Person): Boolean {
return name == other.name
}
fun compare(other: Person) {
knows(other)
this.knows(other)
this knows other
// knows other 错误:没有指定调用方法或无法隐式表达
}
}
适用场景
- 提升代码可读性:当函数代表的是两个对象之间的某种关系时,使用中缀函数能让代码更自然、易读。
- 模拟自定义运算符:借助中缀函数,可以模拟自定义运算符,让代码更具表现力。