Kotlin基础知识_11-中缀表达式_infix
Kotlin基础知识_11-中缀表达式 - infix
1. 中缀表达式
中缀表达式是 Kotlin 中另一个有趣的语法糖。在 Kotlin 中,我们可以使用 infix 关键字将某个函数标记为中缀函数。这意味着我们可以在函数名和参数之间省略点号和括号。 例如,下面的代码展示了如何使用中缀表达式:
定义一个map 集合,使用的是下面的语法:
fun main() {
val values = mapOf("name" to "zhangSan", "age" to 20, "address" to "Beijing")
println("values = $values")
}
这里的to其实不是kotlin的关键字,它其实是一个扩展函数名:
/**
* 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)
只是这个函数使用了 infix关键字进行了修饰,上面的源码中使用定义泛型函数的方式将to()函数定义到了A类型下,并且接收一个B类型的参数。因此A和B可以是两种不同类型的泛型,也就使得我们可以构建出字符串to整型这样的键值对,并返回了一个Pair对象。也就是说,A to B这样的语法结构实际上得到的是一个包含A、B数据的Pair对象,而mapOf()函数实际上接收的正是一个Pair类型的可变参数列表。
自己实现一个infix 函数:
private infix fun String.lengthMax(s: String): Boolean {
return this.length > s.length
}
fun main() {
if ("12345678" lengthMax "fafa") {
println("The expression on the left is longer")
}
}
运行:
The expression on the left is longer.
在实际编码中,中缀表达式常常用于更自然地表达某些操作,例如 and 和 or 操作符:
fun main() {
val a = true
val b = false
val c = a and b // Using infix expression
val d = a or b // Using infix expression
println("c = $c")
println("d = $d")
}
运行;
c = false
d = true
<完>

浙公网安备 33010602011771号