首页 > 解决方案 > Kotlin thinks that two methods have the same JVM signature, but the actually don't

问题描述

I came from the C# background and I know how to implement this in C#, but I'm struggling with Kotlin. I've got 2 extension functions:

fun <T> Foo<T>.myFunction(func: () -> Unit): Foo<T>

and

fun <T> Foo<T>.myFunction(func: () -> Foo<T>): Foo<T>

Clearly, the return type of func is different in both functions. The first function executes it and returns this, the second executes func and returns the result of func. But it gives me an error:

"Platform declaration clash: The following declarations have the same JVM signature".

How to implement this correctly in Kotlin?

标签: kotlin

解决方案


由于类型擦除(用于表示函数参数的内部 类),您的函数在 JVM 中具有冲突的签名;并且您可以通过为它们中的每一个指定一个 JVM 特定名称来解决此问题。在 Kotlin 中,您仍然可以通过原始名称访问它们,但从 Java 或内部实际使用另一个名称。只需在替代版本上使用注释:Function0<T> @JvmName

fun <T> Foo<T>.myFunction(func: () -> Unit): Foo<T>

@JvmName("myfunctionWithFoo")   
fun <T> Foo<T>.myFunction(func: () -> Foo<T>): Foo<T>

推荐阅读