Author profile picture

apply() (scope function)

Overview

The apply() function is a commonly-used scope function defined in the Kotlin standard library. It’s frequently used for initializing an object after instantiation.

Example

val size = "Hello".apply { 
    println(this)
}.length

In this example, the string “Hello” is printed, and then its length is assigned to the size variable.

Characteristics

When the apply() extension function executes:

  • the receiver object that .apply() is called upon is available as this
  • the result will be the receiver object

Initializing an Object

It’s common to use apply() to initialize an object after it’s been created. For example, here’s a chunk of Android code that configures an EditText.

EditText view = new EditText(this);
view.setText("This is an EditText in Java");
view.setVisibility(View.VISIBLE);
view.setSelection(0, 4);

container.addView(view);

After the object is created, there are a few setters that we call on it. The apply() function allows us to create and further initialize an object in a block of code, without the noise of view. on each line.

container.addView(EditText(this).apply {
    setText("This is an EditText in Kotlin")
    visibility = View.VISIBLE
    setSelection(0, 4)
})

Alternatives

Check out the guide, Understanding Kotlin’s let(), also(), run(), and apply() for help figuring out which scope function to use.

Share this article:

  • Share on Twitter
  • Share on Facebook
  • Share on Reddit