当前位置: 代码迷 >> 综合 >> Kotlin-15-中缀表达式(infix)
  详细解决方案

Kotlin-15-中缀表达式(infix)

热度:73   发布时间:2023-10-09 05:39:53.0

目录

1、定义

2、限制条件

3、应用场景

4、自定义中缀表达式


1、定义

中缀表达式就是一个比较特殊的函数,特殊之处在于它不需要普通函数的用 对象名+点+函数名 的方式调函数。而是 对象+函数名+对象 的方式。

中缀表达式函数需要用 infix 修饰符修饰。

 就比如下面的for循环中,until 和step 都是中缀表达式函数,它们的调用方式,就是对象+函数名+对象 的方式。

class TestMain {fun testA() {println("i am testA.")} 
}
fun main() {//普通函数的调用方式val test=TestMain();test.testA()//中缀表达式函数的调用方式for (i in 1 until 100 step 10) {println("i=$i")}
}//until 源码
public infix fun Int.until(to: Int): IntRange {if (to <= Int.MIN_VALUE) return IntRange.EMPTYreturn this .. (to - 1).toInt()
}
//step 源码
public infix fun IntProgression.step(step: Int): IntProgression {checkStepIsPositive(step > 0, step)return IntProgression.fromClosedRange(first, last, if (this.step > 0) step else -step)
}

2、限制条件

  1. 必须是成员函数或者扩展函数;
  2. 必须只有一个参数;
  3. 参数不能是可变参数或默认参数;

3、应用场景

中缀表达式一般应用于两个相同类型对象之间。适合与两个对象比较。

4、自定义中缀表达式

例子1:下面的中缀表达式函数miss就是作为String的扩展函数。

infix fun String.miss(other: String) {println("$this miss $other")
}fun main() {println("我" miss "你") 
}
//输出结果
我 miss 你

例子2:这里就是作为对象的成员函数来声明的

data class Card(var power:Int){infix fun vs(other:Card):String {if (this.power > other.power) {return "i win"} else if (this.power < other.power){return "i lose"}else{return "I'm as strong as you"}}
}
fun main() {val card1=Card(1000)val card2=Card(999)println("card1 vs card2 =${card1 vs card2}")
}
//输出结果
card1 vs card2 =i win