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
gildor
03/06/2018, 8:25 AM
Would be nice to add
inline
gildor
03/06/2018, 8:26 AM
Problem with all such solutions is you need version for multiple arguments.
r
ribesg
03/06/2018, 8:27 AM
I really prefer to just define a variable and have an
if (x == null)
g
gildor
03/06/2018, 8:27 AM
yes, same for me, we don’t have such helper functions in our project
gildor
03/06/2018, 8:27 AM
if just looks better
gildor
03/06/2018, 8:29 AM
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?
gildor
03/06/2018, 8:29 AM
it’s similar to applicative from functional programming
gildor
03/06/2018, 8:31 AM
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)