What are my options if I want to supply a default ...
# announcements
e
What are my options if I want to supply a default value if an object is null when chaining calls?
E.g.
Copy code
(resources?.getString(R.string.foo) ?: "")
    .let { /* ... */ }
Is there any better way? Something like:
Copy code
resources?.getString(R.string.foo)
    .ifNull { "" }
    .let { }
g
for strings / collections there is
orEmpty()
e
But if I want to specify a default value, then there's nothing, right?
j
Couldn't you do
Copy code
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
Yeah. Sort of like default values for parameters in methods.
d
Copy code
(resources?.getString(R.string.foo) ?: "")
    .let { }
inline fun <reified T: Any> T?.defaultIfNull(default: T): T = if (this == null) default else this
a
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
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