Kotlin:使Java函数可调用中缀

ilj*_*jau 3 kotlin

试图将powBigInteger类中的函数作为具有相同名称的中缀函数提供.

问题是现在中pow缀运算符递归调用自身.

是否可以使用与函数同名的中缀运算符使Java函数可调用?

package experiments

import java.math.BigInteger

infix fun BigInteger.pow(x: BigInteger): BigInteger {
    return this.pow(x);
}

fun main(args : Array<String>) {
    val a = BigInteger("2");
    val b = BigInteger("3");

    println(a + b)
    println(a pow b)
}
Run Code Online (Sandbox Code Playgroud)

原因:

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)
Run Code Online (Sandbox Code Playgroud)

mbS*_*ola 7

这是因为当你做的时候:

this.pow(x)

你实际上是在递归你的中缀函数.BigInteger没有带有另一个BigInteger的pow函数 - 这就是你在这里定义的内容.不要忘记,仍然可以使用点运算符调用中缀函数!

你可能想写的是:

infix fun BigInteger.pow(x: BigInteger): BigInteger {
    // Convert x to an int
    return pow(x.longValueExact().toInt())
}

fun main(args : Array<String>) {
    val a = BigInteger("2")
    val b = BigInteger("3")

    println(a + b)
    println(a pow b)
}
Run Code Online (Sandbox Code Playgroud)

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