``` inline fun <T : Any?, R> T.notNullOrElse...
# announcements
r
Copy code
inline fun <T : Any?, R> T.notNullOrElse(notNull: (T) -> R, orElse: (T) -> R): R =
    if (this != null) notNull(this) else orElse(this)

val x: String? = "test"
x.notNullOrElse(
    { println(it) },
    { println("x is null") }
)
g
Would be nice to add
inline
Problem with all such solutions is you need version for multiple arguments.
r
I really prefer to just define a variable and have an
if (x == null)
g
yes, same for me, we don’t have such helper functions in our project
if just looks better
also there is similar case, when you want to check multiple values for null and use them only if everything is not null, you can do this using function like:
Copy code
fun <A, B, C, R> ifNonNull(a: A?, b: B?, c: C?, block: (A, B, C) -> R): R?
it’s similar to applicative from functional programming
but after some concideration we decided that default constructions is enough for us, we don’t have many cases where we need it and usually you can solve it using local varialbes + early return:
Copy code
val a = getA() ?: return
val b = getB() ?: "default b"
val c = getC() ?: error("c is null")
doSomething(a + b + c)