kotlin - 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?
解决方案
由于类型擦除(用于表示函数参数的内部 类),您的函数在 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>
推荐阅读
- javascript - 我如何在不使用任何节点模块的情况下处理多部分表单数据
- javascript - 有 2 个相同的接收值来自一个 Promise:在一种情况下它可以工作,在另一种情况下它给出一个 TypeError: x is not a function
- c# - 是否可以简化以下 Linq 表达式?
- regex - 修改 Robocopy 脚本以读取附加到文件夹中文件的编号,添加一个,并重命名正在复制的文件
- php - 即使我添加另一个值,选项标记中的值属性也设置为 0
- node.js - 在 Js 中将对象 Promise 转换为字符串
- node.js - Node js + TypeSc + Babel“错误:找不到模块'koa'”
- colors - 使用 Alpha 通道/不透明度时颜色变暗
- node.js - Node.js 中的进程是什么
- multithreading - raku 在具有不同参数的线程中调用相同的函数