just drawing a blank here: is the not a shortcut f...
# getting-started
n
just drawing a blank here: is the not a shortcut for
if (predicate(x)) f(x) else null
?
e
you could
Copy code
x.takeIf(::predicate)?.let(::f)
if
x
is not null, but the way you wrote it with
if
is clearer
n
yeah, I had this and it's not nicer, so reverted. But then I thought I missed something like a
Any?.runIf
. Seems I was mistaken
d
We are considering adding
runIf
function to stdlib
Copy code
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
Copy code
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 compiler
1
e
nice. I have written and used an
.applyIf()
extension in several projects (even without smartcasting); I think I would get more use out of that than
runIf()
but it's almost equivalent
s
wouldn't it conform more to the naming convention in Kotlin, if the function was called
runIfOrNull
!?
d
There is no final decision yet about this function