w

    Wesley Hartford

    4 months ago
    Java's
    Map.computeIfAbsent()
    function documentation includes:
    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
    ?
    Klitos Kyriacou

    Klitos Kyriacou

    4 months ago
    (mutableMapOf(1 to "one") as MutableMap<Int, String?>).computeIfAbsent(1) { null }
    Jordan Stewart

    Jordan Stewart

    4 months ago
    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
    Klitos Kyriacou

    Klitos Kyriacou

    4 months ago
    w

    Wesley Hartford

    4 months ago
    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.
    dmcg

    dmcg

    4 months ago
    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