David Kubecka
06/06/2024, 1:13 PMfun <T> test(param: T, func: () -> T) {}
Is there any way to enforce that param and lambda return types are the same? Current version allows calling the function like this
test(1) { "1" }
The reason is that the inferred type is the closest common type. So explicitly specifying the generic type would help but I would like to avoid that if possible.Joshua Hansen
06/06/2024, 10:06 PMfun <T> test(param: T, func: (T) -> T) {
val funcResult = func(param)
}
val test = test(1) { "1" } // Error
David Kubecka
06/07/2024, 7:45 AMDavid Kubecka
06/07/2024, 9:39 AMfun <T, R> test(param1: T, param2: R, func: (T, R) -> Pair<T, R>) {
val funcResult = func(param1, param2)
}
val test = test(1, 2) { _, _ -> "1" } // Error
David Kubecka
06/07/2024, 9:44 AMfun <T, R> test(param1: T, param2: R, func: (Pair<T, R>) -> Pair<T, R>) {
val funcResult = func(param1 to param2)
}
David Kubecka
06/10/2024, 11:42 AMfun <T> test(param: T, func: (T) -> T) {
val funcResult = func(param)
}
val test = test(Unit) { "1" } // compiles ok
Why is that? I thought that Unit
has no special place in the type hierarchy.Youssef Shoaib [MOD]
06/10/2024, 12:04 PMUnit
don't have to explicitly return it. Hence, the "1" expression is ignored, and Unit is returned. IntelliJ should probably report an error that "1" is unusedKlitos Kyriacou
06/10/2024, 12:05 PM{ "1" }
is treated as a function of type () -> Unit
with an expression whose result is not used. Unused results are very common, for example Set.add
returns a Boolean but we are allowed to ignore it, so in the same way "1" returns a String but we ignore it. IntelliJ reports a warning (it's not an error).David Kubecka
06/10/2024, 12:09 PMDavid Kubecka
06/10/2024, 12:10 PM