Kotlin:使Java函数可调用中缀

尝试使用BigInteger类中的pow函数作为具有相同名称的中缀函数。

问题是现在pow缀运算符递归地调用自己。

是否有可能使用与函数名相同的中缀运算符来调用Java函数?

 package experiments import java.math.BigInteger infix fun BigInteger.pow(x: BigInteger): BigInteger { return this.pow(x); } fun main(args : Array) { val a = BigInteger("2"); val b = BigInteger("3"); println(a + b) println(a pow b) } 

原因:

 Exception in thread "main" java.lang.StackOverflowError at kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull(Intrinsics.java:126) at experiments.KotlinTestKt.pow(KotlinTest.kt) at experiments.KotlinTestKt.pow(KotlinTest.kt:6) 

这是因为当你在做:

this.pow(x)

你实际上递归你的中缀函数。 BigInteger没有powfunction,需要另一个BigInteger–这就是你在这里定义的。 别忘了,中缀函数仍然可以用点运算符来调用!

你可能要写的是这样的:

 infix fun BigInteger.pow(x: BigInteger): BigInteger { // Convert x to an int return pow(x.longValueExact().toInt()) } fun main(args : Array) { val a = BigInteger("2") val b = BigInteger("3") println(a + b) println(a pow b) } 

如果你想重用BigInteger的pow方法,我们需要转换为int。 不幸的是,这可能是有损的,可能会溢出。 如果这是一个问题,你可能要考虑编写你自己的pow方法。