以下声明在Kotlin 是合法的.

fun foo(): String = "foo_1"
fun <T> foo(): T = "foo_2" as T

作为字节码,我们得到:

public final static foo()Ljava/lang/String;

// signature <T:Ljava/lang/Object;>()TT;
// declaration: T foo<T>()
public final static foo()Ljava/lang/Object;

It's also possible to call both of these methods from Kotlin.

The problem comes when I'm trying to call any of them from Java:

ClassKt.foo()

不明确的呼叫.两种方法都匹配...

How to avoid such a problem? How to deal with such methods? What if 3-rd party kt library has same issue?

The example above is a synthetic one.

推荐答案

Why does it work with Kotlin to begin with... In Java having two methods like:

private static String test() {
    return "";
}

private static <T> T test() {
    return null;
}

would result in a compile time error. And for java devs this is sort of obvious, these methods would have the same type erasure. But this is rule imposed by javac, not by the JVM where this code runs. So javac does not treat two methods as having only a different return type as overloads. Well, kotlin is a different language and since it runs on the JVM (that expects valid byte-code) it allows treating methods with only the return type being different as overloads. I am yet to look at the byte code and understand how that happens; it also seems that this will work only for generic code, so may be type erasure is slightly different in case of kotlin.

Now, things should be obvious why calling such a method from java fails. Kotlin offers a neat solution for this: @JvmName("someDistinctName"). I am not entirely sure how this works under the hood either... yet, though I assume this will create a bridge method.

EDIT

@JvmName will rename the method at the byte-code level.

Kotlin相关问答推荐

在Kotlin中将ClosedRange字符串转换为List?<>

Kotlin—列出具有不同T的列表之间的操作'

在Mapstruct中重用@映射定义

KMP:未能添加cafe.adriel.voyager依赖项

如何让 LocalDateTime.parse 拒绝 24:00 时间

Kotlin - 什么时候和什么时候不喜欢内联函数,为什么?

垂直滚动条下拉菜单的桌面组合

使用 LazyListScope 嵌套可组合项

JobIntentService 被销毁,当应用程序被销毁时

Kotlin 插件错误:无法为类 org.jetbrains.kotlin.gradle.tasks.KotlinCompile 生成代理类

如何使 TextInputEditText 只读?

如何在 Kotlin 中为变量设置监听器

Mockito 的 argThat 在 Kotlin 中返回 null

Kotlin reflect proguard SmallSortedMap

查找是否在列表中找到具有特定属性值的元素

如何计算Kotlin中的百分比

判断EditText是否为空kotlin android

在多平台子元素中使用kapt

Kotlin - 如何获取注释属性值

如何将 Kotlin 的 `with` 表达式用于可空类型