Thread
#stdlib
    Mark

    Mark

    3 years ago
    What is the more concise way to write
    if (arg == null) null else myfun(arg)
    ? I can only think of
    arg?.let { myfun(it) } ?: null
    but this seems less readable to me.
    gildor

    gildor

    3 years ago
    arg?.let(::myFun)
    You don’t need
    ?:
    Mark

    Mark

    3 years ago
    ah yes, in this case
    arg?.let { myfun(it) }
    so would
    let
    be the appropriate function to use?
    gildor

    gildor

    3 years ago
    if you need a concise way, yes
    but it still not so much readable, requires little bit time to understand, but if you use this approach a lot, it’s actually nice idiom if you use it a lot, especially with method reference
    Mark

    Mark

    3 years ago
    Ok, thanks. I wonder about creating an extension function:
    MyArgClass.myfun() = this?.let {myfun(this)}
    so I can then do
    arg?.myfun()
    ?
    or is that super-weird!
    gildor

    gildor

    3 years ago
    depends on case I suppose. If you have a lot of such usages, why not. It’s like any other
    toSomething
    functions, including stdlib
    Mark

    Mark

    3 years ago
    Another alternative would be to let
    myfun()
    accept a null arg and return null in that case. Is there some general way (contracts?) that a function can declare that a null arg will return null result?
    voddan

    voddan

    3 years ago
    IMHO if a function accepts a
    null
    it should deal with it more intelligently than returning another
    null
    immediately. In your situation an extension on a not-null type is the most obvious way IMO
    arg?.myFunc()
    h

    hmole

    3 years ago
    I think
    run
    instead of
    let
    looks more concise
    gildor

    gildor

    3 years ago
    you cannot use run with method reference