Olaf Gottschalk
12/01/2025, 9:48 AMfun <O : Any> test(doIt: () -> O) {
TODO()
}
fun <O> test(doIt: () -> O?) {
TODO()
}
fun demo() {
test { "" }
test { null }
}
test must exist in two flavors:
• one where the lambda block can return anything that is nullable
• another that must be chosen if the return value cannot be null.
With my declaration as above, I think the compiler can find a matching method for the String and also for the null value: the first must resolve to the nun-nullable version, the second should (it's the only match!) resolve to the second implementation.
But the reality is different, sadly - the one returning null is getting a compiler error: Cannot infer type for type parameter 'O'. Specify it explicitly.
I tried every variation I could think of, nothing works.
Also tried @OverloadResolutionByLambdaReturnType but that also did not change anything.
Is there any trick I need to pull here to teach the compiler to take the second function for nullable lambda return types?Bernd Prünster
12/01/2025, 11:36 AM@Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE")
@kotlin.internal.LowPriorityInOverloadResolution
Also: don't blindly trust the IDE that it isn't working just because there are red squiggly lines 😉Bernd Prünster
12/01/2025, 11:36 AMOlaf Gottschalk
12/01/2025, 11:58 AMBernd Prünster
12/01/2025, 12:22 PMOlaf Gottschalk
12/01/2025, 12:45 PMOlaf Gottschalk
12/01/2025, 12:46 PMBernd Prünster
12/01/2025, 1:07 PMOlaf Gottschalk
12/01/2025, 2:05 PMOlaf Gottschalk
12/01/2025, 2:26 PMtest<String?> { null }
works. But I do not want my users to understand generics and literally anything about the "magic" behind the scenes...Bernd Prünster
12/01/2025, 2:35 PMBernd Prünster
12/01/2025, 2:38 PMOlaf Gottschalk
12/01/2025, 9:03 PM