如何解决接口函数的"Kotlin: Platform declaration clash:"?



编译此接口声明时,出现错误

Kotlin: Platform declaration clash: The following declarations have the same JVM signature (Function(Lkotlin/jvm/functions/Function1;)V): fun Function(action: (Int) -> Unit): Unit defined in IInterface fun Function(action: (String) -> Unit): Unit defined in IInterface

interface IInterface {
fun Function(action: (Int) -> Unit)
fun Function(action: (String) -> Unit)
}

但是当我应用@JvmName属性a时出现错误

Kotlin: '@JvmName' annotation is not applicable to this declaration

interface IInterface {
@JvmName("Function1001")
fun Function(action: (Int) -> Unit)
fun Function(action: (String) -> Unit)
}

我试过把接口改成抽象类,但无济于事。看起来@JvmName只能用于类声明。

解决这个问题的最佳做法是什么?

默认情况下,接口和开放类中不允许使用@JvmName。KT-20068:的评论解释了原因

@JvmName对于可重写签名是有问题的,因为Kotlin和Java中的重写可能开始出现分歧:

interface A {
@get:JvmName("x")
val foo: Foo
}
interface B {
@get:JvmName("y")
val foo: Foo
}
class C: A, B {
// ???
override val foo = ...
}

您可以通过添加来绕过此限制

@Suppress("INAPPLICABLE_JVM_NAME")

但要小心危险。

最新更新