infix关键字标记的函数,可以使用中缀表达式的方式调用。使得在调用方法的时候,不需要dot.也不需要parentheses()。
比如在构造Pair<A,B>对象的时候经常使用to函数来实现
1 | # 使用中缀 |
这样提高了代码易读性
申明inflx方法,只需在普通的方法前面加infix关键字就行,但是需满足以下限制:
- 必须是成员函数或者是扩展函数
- 方法的参数只能有一个,不能使用
vararg - 参数不能有默认值
define and use
define:
1 | class StringNames { |
use:
1 | val stringNames = StringNames() |
bummock
查看编译后的代码:
1 | public final class StringNames { |
1 | public final class TestStringNameKt { |
infix标记的函数被编译成final方法。而调用的时候没有特别的变化,跟普通的函数调用一样。在编译期间给转换成正常的 Java 代码了
precedence
infix的调用跟运算符的调用很像。但是在优先级上是有一些先后区别的。
- 低。
infix比起算术运算符(+,-,*,/),type cast,rangeTo低1 add 2 + 3等价于1 add (2 + 3)10 until n * 2等价于0 until (n * 2)1xs union ys as Set<*>等价于xs union (ys as Set<*>)
- 高。
infix比起 boolean 操作符要高&&与||、is与ina && b xor c等价于a && (b xor c)a xor b in c等价于(a xor b) in c
| Precedence | Title | Symbols |
|---|---|---|
| Highest | Postfix | ++, --, ., ?., ? |
| Prefix | -, +, ++, --, !, label |
|
| Type RHS | :, as, as? |
|
| Multiplicative | *, /, % |
|
| Additive | +, - |
|
| Range | .. |
|
| Infix function | simpleIdentifier |
|
| Elvis | ?: |
|
| Named checks | in, !in, is, !is |
|
| Comparison | <, >, <=, >= |
|
| Equality | ==, !== |
|
| Conjunction | && |
|
| Disjunction | || |
|
| Lowest | Assignment | =, +=, -=, *=, /=, %= |
this
infix函数需要指定调用者以及参数。如果在调用者内部调用infix方法需要显示的使用this。
1 | class StringCollection { |