https://kotlinlang.org logo
#announcements
Title
# announcements
j

John

11/03/2019, 5:26 PM
Is there a kotlin function to scope an object on a condition? Something like
withIf(myObject.propertyToFiler == true) { myObject -> ... }
m

molikuner

11/03/2019, 5:29 PM
A function with this signature would be impossible, as you just pass a boolean to it. You could use:
Copy code
if (myObject.propertyToFiler == true) with(myObject) { myObject -> ... }
Or if you need a function:
Copy code
inline fun <T, R : Any> withIf(x: T, access: Boolean, block: (T) -> R) = if (access) with(x, block) else null
s

streetsofboston

11/03/2019, 5:51 PM
There are stdlib functions
takeIf
and
takeUnless
. https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/take-if.html
👍 2
💯 2
j

John

11/03/2019, 6:24 PM
Ah,
takeIf
is that I thought I’d seen before
But molikuner’s function is actually a nicer solution