I find myself using destructuring declarations and delegation more and more.
Separating the idea’s, I get these:
1. Destructuring property declarations
class Foo {
val (x, y) = Pair(1, 2) // Class level properties with destructuring
}
2. Delegation to destructured variables
fun main(args: Array<String>) {
val (a, b) by lazy { Pair(1, 2) } // Delegating with destructure
}
3. Nesting destructuring
// (I'm not a fan)
#1 and #2 are the most interesting to me. Still, I’m not sure there are no good alternatives to these cases. IMHO, in order to justify an addition like #1 or #2, there should be no good alternative.
Here’s the simplified workaround by @cabman. The downside here is that one has to save the lazy delegate (or alternatively, the raw things
) to a private variable and must add custom getters to each property:
fun threeThings() = Triple(1, 2, 3)
class Foo {
private val things by lazy { threeThings() }
val x: Int get() = things.first
val y: Int get() = things.second
val z: Int get() = things.third
}
@cabman, As far as getters and setters for #1, I’m not sure I like the idea. But I do think it’s worth considering #1, getters and setters come after.