https://kotlinlang.org logo
#getting-started
Title
# getting-started
n

nkiesel

02/04/2022, 8:39 PM
just drawing a blank here: is the not a shortcut for
if (predicate(x)) f(x) else null
?
e

ephemient

02/04/2022, 8:42 PM
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

nkiesel

02/04/2022, 8:55 PM
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

dmitriy.novozhilov

02/05/2022, 10:09 AM
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

ephemient

02/06/2022, 10:35 AM
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

Stephan Schroeder

02/07/2022, 7:23 AM
wouldn't it conform more to the naming convention in Kotlin, if the function was called
runIfOrNull
!?
d

dmitriy.novozhilov

02/07/2022, 7:31 AM
There is no final decision yet about this function
6 Views