https://kotlinlang.org logo
w

Wesley Hartford

05/05/2022, 7:43 PM
Java's
Map.computeIfAbsent()
function documentation includes:
Copy code
If the mapping function returns {@code null}, no mapping is recorded.
However, when calling this function from Kotlin code, the mapping function has a signature
(K) -> V
, meaning that the passed in function cannot return
null
. Is there any way to use
computeIfAbsent
from kotlin passing a function which may return
null
?
k

Klitos Kyriacou

05/06/2022, 8:16 AM
Copy code
(mutableMapOf(1 to "one") as MutableMap<Int, String?>).computeIfAbsent(1) { null }
j

Jordan Stewart

05/06/2022, 8:40 AM
this does seem a bit odd to me -- Kotlin allows
null
for
compute
and
computeIfPresent
. Why the difference? the only difference in signature is that they're
BiFunction
rather than
Function
if we define our own type
we don't see the same compilation failure
interesting
k

Klitos Kyriacou

05/06/2022, 8:58 AM
w

Wesley Hartford

05/06/2022, 2:59 PM
Thanks for the replies, I ran across that discuss thread as well and though it seems like a strange decision. Not necessarily a bad one, but odd to have a case where the same function can't be used in the same ways from Kotlin as from Java. I ended up replacing the call with the
compute
function.
d

dmcg

05/06/2022, 3:04 PM
I’d wondered where some of these pragmatic special cases came from, it’s good to see that they are at least visible if you know where to look
61 Views