I'm booting up on Kotlin and looking to configure an Array
of Label
s in the pattern of a builder syntax. I came up with the Kotlin standard library function (apply
) combined with a helper function on collections (forEach
). Is it correct to refer to this as builder pattern? What that means to me is that the declaration, assignment and the configuration are done in one line/step. I appreciate any thoughts about how to write this in a still more compact and clear "Kotlin-ish" way, or is this the preferred Kotlin syntax more or less. BTW, there are a lot of ways to get this wrong (use let
instead of apply
does not return the receiver).
val labels = arrayOf(Label("A"),Label("B"),Label("C"),Label("D")).apply {
this.forEach { it.prefWidth = 50.0 }
}
What I'd suggest is avoiding repeating the word Label
in your idiom:
val labels = arrayOf("A", "B", "C", "D")
.map { Label(it).apply { prefWidth = 50.0 } }
.toTypedArray()
This creates a bit more transient objects, but it reduces the noise and makes it easier to see the thing that varies between your labels.