liveBook · Manning

Apply

As explained in Kotlin in Action, 2E

apply is a Kotlin standard-library scope function that executes a lambda with the receiver as its implicit receiver and returns that receiver.

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

How Kotlin in Action, 2E covers it

How deep it goes
Defines receiver scope, implicit calls, extension usage, and receiver-return semantics through worked Kotlin examples.
Examples
Uses StringBuilder alphabet construction and Android TextView configuration as concrete applications.
What it assumes
Assumes familiarity with Kotlin lambdas and objects while introducing receiver lambdas through simple examples.
What you can do after
Build and initialize Kotlin objects compactly with receiver lambdas that return the configured instance.
How it connects
Connects lambdas with receivers, with, builder-style APIs, Java Builder objects, and buildString.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.