Take a look at the following code.
fun stuff(func: () -> Int) {
println(func().toString())
}
fun stuff(func: () -> String) {
println(func())
}
fun main() {
stuff { 1 }
}
This gives me a strange error.
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
I'm unsure why and trying to solve this. I could use Java Generics, but I'd like this work in pure kotlin. Could also do something with parameterized typing like
fun <T>stuff(func: () -> T)
But this isn't as elegant if the caller of stuff is unaware of what it's passing in.
I also saw this answer: Failsafe withFallback(): why kotlin compiler fails to infer lambda type?
This doesn't work due to the following error:
Duplicate method name "stuff" with signature "(Lkotlin.jvm.functions.Function0;)V"
So Based on this error I'm guessing doing this as I'd like is impossible... But I'm hopeful!
Would love some thoughts here.