Is there a kotlin function to scope an object on a...
# announcements
j
Is there a kotlin function to scope an object on a condition? Something like
withIf(myObject.propertyToFiler == true) { myObject -> ... }
m
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
There are stdlib functions
takeIf
and
takeUnless
. https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/take-if.html
👍 2
💯 2
j
Ah,
takeIf
is that I thought I’d seen before
But molikuner’s function is actually a nicer solution