kotlin-中缀表达式

412 阅读1分钟

中缀表达式的语法是在扩展函数的基础上的。它需要在函数前面加上infix修饰。

普通扩展函数

public fun Int.to(that: Int): Pair<Int,Int> = Pair(this, that)

调用

2.to(3)

infix修饰的扩展函数

public infix fun Int.to(that: Int): Pair<Int,Int> = Pair(this, that)

调用

2 to 3

中缀表达式的要求:

  • 中缀表达式必须是扩展函数或方法
  • 中缀表达式只能有一个参数
  • 中缀表达式的参数不能有默认值(否则参数可能为空);
  • 中缀表达式的参数不能是可变参数(否则参数可能不止一个)。