【发布时间】:2021-03-29 19:18:43
【问题描述】:
看看下面的代码。
fun stuff(func: () -> Int) {
println(func().toString())
}
fun stuff(func: () -> String) {
println(func())
}
fun main() {
stuff { 1 }
}
这给了我一个奇怪的错误。
Overload resolution ambiguity: public fun stuff(func: () -> Int): Unit defined in root package in file File.kt public fun stuff(func: () -> String): Unit defined in root package in file File.kt
'return' is not allowed here
The integer literal does not conform to the expected type Unit
我不确定为什么并试图解决这个问题。我可以使用 Java 泛型,但我希望在纯 kotlin 中进行这项工作。也可以用参数化类型来做一些事情,比如
fun <T>stuff(func: () -> T)
但是如果调用者不知道它传递了什么,这就不那么优雅了。
我也看到了这个答案:Failsafe withFallback(): why kotlin compiler fails to infer lambda type?
由于以下错误,这不起作用:
Duplicate method name "stuff" with signature "(Lkotlin.jvm.functions.Function0;)V"
因此,基于此错误,我猜想按照自己的意愿执行此操作是不可能的...但我充满希望!
会喜欢这里的一些想法。
【问题讨论】:
-
我认为它不适用于 java 泛型:Producer
和 Producer 都被编译为 Producer。我认为这也可能是不幸的是它在 kotlin 中不起作用的原因......