Collection Linker Syntax in Kotlin

I boot into Kotlin and want to customize Arrayof Labelin the linker syntax template. I came up with the standard Kotlin ( apply) library function in combination with the helper function in collections ( forEach). Is it right to refer to the build template? For me, this means that the declaration, purpose, and configuration are done in one line / step. I appreciate any thoughts on how to write this in an even more compact and understandable "Kotlin-ish" form, or is this the preferred Kotlin syntax more or less. By the way, there are many ways to do this wrong (use letinstead applydoes not return the recipient).

val labels = arrayOf(Label("A"),Label("B"),Label("C"),Label("D")).apply {
    this.forEach { it.prefWidth = 50.0 }
}
+4
source share
3

Label :

val labels = arrayOf("A", "B", "C", "D")
        .map { Label(it).apply { prefWidth = 50.0 } }
        .toTypedArray()

, , .

+4

forEach map apply, :

arrayOf(Label("A"), Label("B"), Label("C"), Label("D"))
    .map { it.apply { prefWidth = 50.0 } }

apply idiom ( Builder ).

, map. / .


, , , :

inline fun <T> Array<T>.applyEach(action: T.() -> Unit) = apply { forEach { it.action() } }

//usage
val labels = arrayOf(Label("A"), Label("B"), Label("C"), Label("D")).applyEach { prefWidth = 50.0 }
+3

The functions inside are Standard.ktreally confusing, but you are using apply()it correctly : it is best used when initializing a variable. You can completely refer to this as a Builder template, as it provides a clean solution for building an instance of a class.

+2
source

Source: https://habr.com/ru/post/1694114/


All Articles