Kotlin’s apply scope function runs a lambda with the target object as its implicit receiver, then returns that same object. It is useful for constructing and configuring objects without repeating their reference. section 5.4 section 5.4.2
Configure an object immediately
fun createViewWithCustomAttributes(context: Context) = TextView(context).apply { text = "Sample Text" textSize = 20.0 setPadding(10, 0, 0, 0) } Inside the lambda, the TextView is the receiver, so its properties and methods need no qualifier. After configuration, apply returns the initialized TextView.
Use apply when the lambda primarily configures the receiver:
- Call it as an extension function on the object being configured. section 5.4.2
- Call methods and assign properties directly inside the receiver lambda. section 5.4
- Prefer with when the final lambda expression should become the result; apply always returns the receiver. section 5.4.1
- Recognize apply as a builder-style alternative to a separate Java Builder object. section 5.4.2
