Sobes.tech
Junior

What is the purpose of the 'apply' function in Kotlin?

sobes.tech AI

Answer from AI

The apply function belongs to the standard scoped functions in Kotlin.

Purpose:

  • Executes a block of code on the calling object.
  • Returns the object itself after applying the block.
  • Inside the block, the object is accessible as this.

Used for:

  • Configuring and initializing objects, especially those with many properties to set.
  • Improving code readability by allowing method chaining or property setting on a single object.

Example:

// Create an object and configure it using apply
val textView = TextView(context).apply {
    text = "Hello, world!"
    textSize = 16f
    setTextColor(Color.BLACK)
    setPadding(10, 10, 10, 10)
}

// textView is now a configured instance of TextView

Key difference from let, run, with:

Function Receiver in block Return value
apply this (object) Object
let it (object) Result of the last expression in the block
run (as extension) this (object) Result of the last expression in the block
with this (object) Result of the last expression in the block
What is the purpose of the 'apply' function in… - sobes.tech