https://kotlinlang.org logo
#stdlib
Title
# stdlib
m

Mark

11/30/2018, 7:23 AM
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

gildor

11/30/2018, 7:24 AM
arg?.let(::myFun)
You don’t need
?:
m

Mark

11/30/2018, 7:26 AM
ah yes, in this case
arg?.let { myfun(it) }
so would
let
be the appropriate function to use?
g

gildor

11/30/2018, 7:26 AM
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

Mark

11/30/2018, 7:29 AM
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

gildor

11/30/2018, 7:30 AM
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

Mark

11/30/2018, 7:35 AM
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

voddan

11/30/2018, 7:43 AM
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

hmole

11/30/2018, 1:38 PM
I think
run
instead of
let
looks more concise
g

gildor

11/30/2018, 2:04 PM
you cannot use run with method reference
4 Views