Skip to content
DeveloperMemos

Kotlin's apply Explained

Kotlin, Android Development2 min read

When developing Android applications with Kotlin, it is common to come across scenarios where you need to initialize an object and configure its properties. Kotlin provides a convenient function called apply that allows you to initialize an object and configure its properties in a concise and readable way. In this article, we will delve into the details of apply and demonstrate its usage through examples.

Understanding apply

The apply function is an extension function defined on any object in Kotlin. It takes a lambda expression as its argument, allowing you to access and modify the properties of the object within the lambda. The return value of the apply function is the object itself, which enables method chaining.

The syntax for using apply is as follows:

1objectName.apply {
2 // Property configurations
3}

Simplifying Object Initialization

One of the main use cases for apply is simplifying object initialization. Instead of creating an object and then setting its properties one by one, you can use apply to combine both steps into a single expression.

Let's consider an example where we want to create a TextView in Android and set its text, text size, and color programmatically:

1val textView = TextView(context).apply {
2 text = "Hello World"
3 textSize = 18f
4 setTextColor(Color.BLACK)
5}

By using apply, we can create the TextView object and configure its properties in a concise and readable manner.

Configuring Builder Objects

In Android development, builder patterns are commonly used to construct complex objects with many optional parameters. The apply function can greatly simplify the configuration of builder objects.

For instance, if you have a AlertDialog.Builder in Android and want to set its title, message, and positive button, you can use apply as follows:

1val alertDialog = AlertDialog.Builder(context).apply {
2 setTitle("Confirmation")
3 setMessage("Are you sure?")
4 setPositiveButton("Yes") { dialog, _ ->
5 // Handle positive button click
6 }
7}.create()

Here, we create an AlertDialog.Builder object, configure its properties using apply, and chain the create() method at the end to obtain the final AlertDialog.

Applying Extensions and Properties

The apply function is not limited to configuring built-in classes or builders. It can also be used to apply extensions and properties to an object. This allows you to add custom functionality or modify existing properties in a convenient way.

Consider the following example where we define an extension function called makeToast() on the Context class in Android. With apply, we can easily apply this extension function to a Context object:

1context.apply {
2 makeToast("Hello Kotlin!")
3}

In this case, makeToast is an extension function that displays a toast message. By using apply, we can directly invoke makeToast on the Context object without explicitly assigning it to a variable.

Conclusion

Kotlin's apply function provides a concise and expressive way to initialize objects, configure their properties, and apply extensions or properties to them. By leveraging apply, you can write clean and readable code while reducing boilerplate. Take advantage of this powerful function in your Android development projects to enhance code maintainability and productivity.