Kotlin: make Java function callable infix

前端 未结 1 1395
醉话见心
醉话见心 2021-01-19 16:56

Tried to make pow function from BigInteger class available as infix function with the same name. The problem is that now the pow infix operator cal

相关标签:
1条回答
  • 2021-01-19 17:24

    This is because when you're doing:

    this.pow(x)

    You're actually recursing your infix function. BigInteger doesn't have pow function that takes another BigInteger-- that's what you're defining here. And don't forget, infix functions can still be called with the dot operator!

    What you probably meant to write was this:

    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)
    }
    

    If you want to reuse BigInteger's pow method, we need to convert to an int. Unfortunately, this is potentially lossy and may overflow. You might want to consider writing your own pow method if this is a concern.

    There is no way to mark a Java method "natively" as infix. You can only accomplish this by using a wrapper.

    0 讨论(0)
提交回复
热议问题