https://kotlinlang.org logo
Title
e

Edgars

10/30/2018, 2:47 PM
What are my options if I want to supply a default value if an object is null when chaining calls?
E.g.
(resources?.getString(R.string.foo) ?: "")
    .let { /* ... */ }
Is there any better way? Something like:
resources?.getString(R.string.foo)
    .ifNull { "" }
    .let { }
g

gergo

10/30/2018, 2:49 PM
for strings / collections there is
orEmpty()
e

Edgars

10/30/2018, 2:51 PM
But if I want to specify a default value, then there's nothing, right?
j

Joris PZ

10/30/2018, 2:54 PM
Couldn't you do
resource?.getString(R.string.foo)
   ?.let {

   }
   ?: "default"
👍 1
Oh wait, I see in OP's version the lambda in
let
would be executed on the default value, which doesn't happen in my version...
e

Edgars

10/30/2018, 2:57 PM
Yeah. Sort of like default values for parameters in methods.
d

dave08

10/30/2018, 2:59 PM
(resources?.getString(R.string.foo) ?: "")
    .let { }
inline fun <reified T: Any> T?.defaultIfNull(default: T): T = if (this == null) default else this
a

agrosner

10/30/2018, 3:09 PM
would be nice to have something like in Swift where you only need to supply the first
?
on the object. the subsequent
?
are cluttery
g

gildor

10/31/2018, 1:43 AM
I like current explicit behaviour more. Otherwise you have problems with extension function with nullable receiver There is discussion on Kotlin Forum about this, as I remember