gpt4 book ai didi

java - 标记功能参数时为“overload resolution ambiguity”

转载 作者:行者123 更新时间:2023-12-02 12:37:59 34 4
gpt4 key购买 nike

这是我的Kotlin(1.3.61版本)+ Java(1.8.0_201)代码无法编译:

Maven:

<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>2.0.1</version>
</dependency>

Test.Kt:
fun main(args: Array<String>) {
Point().setX(1)
}

Point.java:
import javax.annotation.Nonnull;

public class Point {
public void setX(int x) {
}

public void setX(@Nonnull Integer x) {
}
}

由于出现以下错误而无法编译:
Error:(2, 13) Kotlin: Overload resolution ambiguity: 
public open fun setX(@Nonnull x: Int): Unit defined in Point
public open fun setX(x: Int): Unit defined in Point

如果我在第二个 @NonNull函数中删除了 setX批注,则此演示可以编译。我以为Java批注只是多余的元数据,不会影响代码本身,所以我不知道为什么在这里出现歧义。

另外,我运行 javap -s Point.class,发现它们具有相同的输出:
public void setX(java.lang.Integer);
descriptor: (Ljava/lang/Integer;)V

有人可以帮忙解释一下发生了什么吗?提前致谢。

最佳答案

来自 Kotlin 的行动

sometimes Java code contains information about nullability, expressed using annotations. When this information is present in the code, Kotlin uses it. Thus @Nullable String in Java is seen as String? by Kotlin, and @NotNull String is just String. The interesting question is what happens when the annotations aren’t present. In that case, the Java type becomes a platform type in Kotlin.

When you use Java declarations from Kotlin, Java primitive types become non-null types (not platform types), because they can’t hold null values.



在您的情况下,第一种方法具有java primitve类型作为参数和 ,因为基元不能为空 kotlin将其转换为
setX(x: Int)

并且由于第二种方法包含@Nonnull批注,因此kotlin使用此信息,因此将方法转换为
setX(x: Int)

因此,正如您对kotlin所看到的那样,它们是两种具有完全相同签名的不同方法,因此模棱两可。

关于java - 标记功能参数时为“overload resolution ambiguity”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59641238/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com