What is the more concise way to write `if (arg == ...
# stdlib
m
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.
g
arg?.let(::myFun)
You don’t need
?:
m
ah yes, in this case
arg?.let { myfun(it) }
so would
let
be the appropriate function to use?
g
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
m
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!
g
depends on case I suppose. If you have a lot of such usages, why not. It’s like any other
toSomething
functions, including stdlib
👍 1
m
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?
v
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()
👍 2
2
h
I think
run
instead of
let
looks more concise
g
you cannot use run with method reference