Skip to content

中缀函数

1. 什么是中缀函数

在kotlin中,中缀函数是一种特殊类型的函数,可以使用中缀符号(不需要点符合和圆括号)来调用函数。

中缀函数需要满足三个条件:

  1. 必须是成员函数或者扩展函数
  2. 只能有一个参数
  3. 必须使用 infix 关键字标记

2. 中缀函数如何定义

kotlin
infix fun 类型.函数名(参数: 参数类型): 返回类型 {
    // 函数体
}

示例 1:使用中缀函数进行数值加法

kotlin
class Number(val value: Int)

infix fun Number.add(other: Number): Number {
    return Number(this.value + other.value)
}

fun main() {
    val num1 = Number(10)
    val num2 = Number(20)
    
    // 使用中缀符号调用
    val result = num1 add num2
    
    println(result.value) // 输出:30
}

示例 2:扩展函数作为中缀函数

kotlin
infix fun String.concatWith(other: String): String {
    return this + other
}

fun main() {
    val result = "Hello" concatWith " World"
    println(result) // 输出:Hello World
}

实例三:两个向量的点积运算的中缀函数

kotlin
class Vector(val x: Int, val y: Int) {
    infix fun dot(other: Vector): Int {
        return this.x * other.x + this.y * other.y
    }
}

fun main() {
    val v1 = Vector(2, 3)
    val v2 = Vector(4, 5)

    // 使用中缀函数
    val result = v1 dot v2  // 等价于 v1.dot(v2)
    println(result)  // 输出 23
}

另外,中缀函数常用于一些操作符重载场景或语义上清晰的二元操作,如: to:用于创建键值对。

kotlin
val pair = "key" to "value"  // 使用内置的 `to` 中缀函数创建键值对

Released under the MIT License.