Destructuring: Suppose I have a function like this...
# getting-started
m
Destructuring: Suppose I have a function like this:
Copy code
fun childVisible(left: Int, top: Int, right: Int, bottom: Int): Boolean
and I want to pass in the properties of an Android
Rect
. Is there a way to do the following more concisely?
Copy code
val (childLeft, childTop, childRight, childBottom) = childRect
return childVisible(childLeft, childTop, childRight, childBottom)
a
if we're playing golf,
Copy code
return childRect.run { childVisible(left, top, right, bottom) }
or alternatively
with(childRect) { ... }
if you don't need the fluent chaining style
but this is a pretty great way to write unreadable code if overused 🙂
👍 2
m
Thanks! I think this is better, because now there’s only one chance to screw up the order, rather than two.
a
might as well make it a function that overloads
childVisible
though if you're going to use this in enough places where you're worried about getting the order wrong
👍 2
m
also consider using named parameters to reduce the chance of misplacing actual parameters
m
Another option would be to make an extension function on
Rect
, which calls
childVisible
with the correct arguments
👍 1
d
I may well just use
(l, t, r, b)
☝️ 1