y
10/18/2022, 11:30 AMvar maybe_null = if (condition) { method_chain_that_may_return_null() } else { null }
dmitriy.novozhilov
10/18/2022, 11:35 AMinline fun <R> runIf(condition: Boolean, block: () -> R): R? = if (condition) block() else null
dmitriy.novozhilov
10/18/2022, 11:37 AMval 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
10/18/2022, 11:40 AMNicolas Chaduc
10/18/2022, 11:52 AMtakeIf { condition }?.run {
method_chain_that_may_return_null()
}
Joffrey
10/18/2022, 2:47 PMvar maybeNull = method().chain()?.takeIf(condition)
Stephan Schroeder
10/22/2022, 5:55 PMmaybeNull
should probably defined with val
assuming you're not chaning it later.gildor
10/25/2022, 4:00 PM