nkiesel
02/04/2022, 8:39 PMif (predicate(x)) f(x) else null
?ephemient
02/04/2022, 8:42 PMx.takeIf(::predicate)?.let(::f)
if x
is not null, but the way you wrote it with if
is clearernkiesel
02/04/2022, 8:55 PMAny?.runIf
. Seems I was mistakendmitriy.novozhilov
02/05/2022, 10:09 AMrunIf
function to stdlib
fun <T> runIf(cond: Boolean, block: () -> T): T? = if (cond) block() else null
But this function requires new kind of contracts which allows to propagate smartcast info from condition to lambda body
fun test(x: String?) {
val y = runIf(x != null) {
x.length // should be smartcast to String
}
}
And those new contracts will be possible to implement only in K2 compilerephemient
02/06/2022, 10:35 AM.applyIf()
extension in several projects (even without smartcasting); I think I would get more use out of that than runIf()
but it's almost equivalentStephan Schroeder
02/07/2022, 7:23 AMrunIfOrNull
!?dmitriy.novozhilov
02/07/2022, 7:31 AM