Author profile picture

apply() (scope function)


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.


val size = "Hello".apply { 

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


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.setSelection(0, 4);


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)


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

Share this article: