参考:
val map = mapOf(
1 to "one",
2 to "two",
3 to "three"
)
点击to 可看到是一个中缀方法:
public infix fun <A, B> A.to(that: B): Pair<A, B> = Pair(this, that)
infix函数(中缀方法):
infix函数(中缀方法)需要几个条件:
-
只有
一个参数
-
在方法前必须加
infix
关键字 -
必须是
成员方法
或者扩展方法
测试一:
//扩展函数
infix fun Int.add(x: Int): Int {
return this + x
}
//成员函数
class Account {
var balance = 100.0
infix fun add(amount: Double) = run { this.balance = balance + amount }
}
fun main() {
println(100 add 200)
//300
Account().apply {
this add 200.00
println(this.balance)
//300.0
}
}
测试二:
fun main() {
println("北京" 中缀 "上海")
//啦啦啦,我是中缀函数,实例是:【北京】,我的唯一参数是【上海】
println(TestInfix().useInfix)
//啦啦啦,我是中缀函数【TestInfix@24d46ca6】,我的唯一参数是【上海】
}
/**
*自定义中缀函数--->(扩展函数)
* 1.使用infix在fun前修饰
* 2.只能有一个参数(uniqueParam)
* 3.是二元的的,参数1:实例(北京);参数二:参数
*/
infix fun String.中缀(uniqueParam: String): String =
"啦啦啦,我是中缀函数,实例是:【$this】,我的唯一参数是【$uniqueParam】"
class TestInfix {
/**
*自定义中缀函数--->(成员函数(class中))
* 1.使用infix在fun前修饰
* 2.只能有一个参数(uniqueParam)
*/
infix fun 中缀(uniqueParam: String): String =
"啦啦啦,我是中缀函数【$this】,我的唯一参数是【$uniqueParam】"
/**
* 调用中缀函数
*/
var useInfix = 中缀("上海")
}