在学习如何创建具有中缀表示法的函数之前,让我们先了解两个常用的中缀函数。
当你使用 ||
和 &&
操作时,编译器会查找 or 和 and 函数,并在后台调用它们。
这两个函数都支持中缀表示法。
示例:Kotlin or & and 函数
fun main(args: Array<String>) {
val a = true
val b = false
var result: Boolean
result = a or b // a.or(b)
println("result = $result")
result = a and b // a.and(b)
println("result = $result")
}
运行程序后,输出将是
result = true result = false
在上面的程序中,使用了 a or b
而不是 a.or(b)
,以及 a and b
而不是 a.and(b)
。这是因为这两个函数都支持中缀表示法。
如何创建具有中缀表示法的函数?
在 Kotlin 中,如果一个函数满足以下条件,就可以使用中缀表示法来调用它:
- 它是一个成员函数(或扩展函数)。
- 它只有一个参数。
- 它用
infix
关键字标记。
示例:用户定义的具有中缀表示法的函数
class Structure() {
infix fun createPyramid(rows: Int) {
var k = 0
for (i in 1..rows) {
k = 0
for (space in 1..rows-i) {
print(" ")
}
while (k != 2*i-1) {
print("* ")
++k
}
println()
}
}
}
fun main(args: Array<String>) {
val p = Structure()
p createPyramid 4 // p.createPyramid(4)
}
运行程序后,输出将是
*
* * *
* * * * *
* * * * * * *
在这里,createPyramid()
是一个创建金字塔结构的函数,它使用了中缀表示法。它是类 Structure
的成员函数,只接受一个类型为 Int
的参数,并以 infix
关键字开头。
金字塔的行数取决于传递给函数的参数。