Kotlin:使Java函数可调用中缀 [英] Kotlin: make Java function callable infix

查看:163
本文介绍了Kotlin:使Java函数可调用中缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图将BigInteger类中的pow函数用作具有相同名称的infix函数.问题在于,现在pow中缀运算符会递归地调用自身.

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 calls itself recursively.

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

Is it possible to make Java function callable using infix operator with same name as function?

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

原因:

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)

如果我正在定义自己的Java类(而不是使用库类),是否可以将Java方法标记为中缀?也许是注释?

If I were defining my own Java class (rather than using a library class), is there any way to mark the Java method as infix? Perhaps an annotation?

推荐答案

这是因为您在进行以下操作:

This is because when you're doing:

this.pow(x)

您实际上是在递归您的infix函数. BigInteger没有pow函数需要另一个BigInteger,这就是您在此处定义的功能.而且请记住,仍然可以使用点运算符来调用中缀函数!

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

如果要重用BigInteger的pow方法,则需要转换为int.不幸的是,这潜在地有损并且可能溢出.如果您对此感到担忧,则可能需要考虑编写自己的pow方法.

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.

无法将Java方法本地"标记为中缀.您只能使用包装器来完成此操作.

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

这篇关于Kotlin:使Java函数可调用中缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆