is there a more compact way to do this? `var maybe...
# getting-started
y
is there a more compact way to do this?
var maybe_null = if (condition) { method_chain_that_may_return_null() } else { null }
d
Copy code
inline fun <R> runIf(condition: Boolean, block: () -> R): R? = if (condition) block() else null
Ideally we want to add this function to stdlib, but it requires a new kind of contracts, because in this form compiler won't propagate smartcasts into block
Copy code
val x: String? = ...

val y = if (x != null) { 
    x.length // smartcast to String
} else null

val z = runIf(x != null) {
    x.length // no smartcast, compile error
}
Most likely we will support such contracts in K2 compiler, so
runIf
will be added to stdlib (BTW naming is not final)
y
I see. thank you. that was the approach I was going with and it’s nice to see that it’s idiomatic
n
If method_chain_that_may_return_null() not need condition to smartcasts you can write it like this :
Copy code
takeIf { condition }?.run {
  method_chain_that_may_return_null()
}
j
Note that if the method chain has no side effect and its performance is not a concern, you can also simply write:
Copy code
var maybeNull = method().chain()?.takeIf(condition)
s
maybeNull
should probably defined with
val
assuming you're not chaning it later.
1
g
I always prefer if/else, it's easier to read and a lot more extendable, for example I often want to add logs in case of null, if requires just add logs instead of rewriting existing code from some kind runIf