Kotlin之中缀调用函数


infix function

  对于infix function,其实我们之前已经遇到过了。不知道你对于kotlin的map的使用还有没有印象:

fun main(args: Array<String>) {
    val map = mapOf(1 to "one", 2 to "two")
    map.map(::println)
}
//result:
1=one
2=two

Process finished with exit code 0

  这val map = mapOf(1 to "one", 2 to "two")里的to就是一个infix function。其源码实现:public infix fun <A, B> A.to(that: B): Pair<A, B> = Pair(this, that)
  调用方式有两种:
  1.to("one"):常规调用方式
  1 to "one:中缀表示法调用