DEV Community

James Ade
James Ade

Posted on

Some Powerful Functions in Kotlin You need to know

Kotlin Functions

1. Let

Kotlin's let function is a helpful tool for performing actions on objects within a given scope. It is often used to execute a block of code on an object only if the object is not null, avoiding the need for null check conditions.

The let function is a higher-order function that allows you to execute a block of code on an object, and then return the object itself. It is particularly useful when you need to perform a series of operations on an object, but don't want to clutter your code with null checks.

Here's an example of how you might use the let function in Kotlin:

fun sendEmail(email: String) {
    val emailRegex = Regex(pattern = "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,6}$")
    email.let {
        if (emailRegex.matches(it)) {
            // send email
        } else {
            throw IllegalArgumentException("Invalid email address")
        }
    }
}


Enter fullscreen mode Exit fullscreen mode

In this example, we use the let function to perform a null check on the email parameter. If the email is not null, we proceed to verify that it is in the correct format using a regular expression. If the email is invalid, we throw an exception. Otherwise, we proceed to send the email.

One of the benefits of using the let function is that it allows you to avoid having to write boilerplate null check code. It also makes your code more readable, as it clearly separates the null check logic from the rest of the code.

Another way you can use the let function is to chain multiple operations together. For example:

fun processData(data: Data?) {
    data?.let {
        it.transform()
        it.validate()
        it.save()
    }
}

Enter fullscreen mode Exit fullscreen mode

In this example, we use the let function to perform a null check on the data parameter. If data is not null, we execute a series of operations on it. This allows us to avoid having to write a null check for each operation, which makes our code more concise and easier to read.

2. Also

The also function is a higher-order function that allows you to execute a block of code on an object, and then return the object itself. It is similar to the let function, with the main difference being that the also function passes the object itself as a parameter to the block of code, rather than the result of the block.

Here's an example of how you might use the also function in Kotlin:

fun processData(data: Data) {
    data.also {
        it.transform()
        it.validate()
    }.save()
}
Enter fullscreen mode Exit fullscreen mode

In this example, we use the also function to perform a series of operations on the data object. First, we transform and validate the data. Then, we use the save function to save the processed data.

One of the benefits of using the also function is that it allows you to chain multiple operations together in a concise and readable way. It also makes it easy to perform operations on an object before and after performing some other action on it.

Another way you can use the also function is to perform null checks and execute code only if the object is not null. For example:

fun sendEmail(email: String?) {
    email?.also {
        if (it.isNotEmpty()) {
            // send email
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

In this example, we use the also function to perform a null check on the email parameter. If email is not null, we proceed to check if it is empty. If it is not empty, we proceed to send the email. This allows us to avoid having to write separate null and empty check logic, which makes our code more concise and easier to read.

3. Run

The run function is a higher-order function that allows you to execute a block of code on an object, and then return the result of the block. It is similar to the let function, with the main difference being that the run function returns the result of the block, rather than the object itself.

Here's an example of how you might use the run function in Kotlin:

fun getData(): Data {
    val data = Data()
    return data.run {
        transform()
        validate()
        this
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, we use the run function to perform a series of operations on the data object. First, we transform and validate the data. Then, we return the data object itself.

One of the benefits of using the run function is that it allows you to chain multiple operations together in a concise and readable way, and then return the result of those operations. It is particularly useful when you need to perform a series of operations on an object, and then return a value based on the result of those operations.

Another way you can use the run function is to perform null checks and execute code only if the object is not null. For example:

fun sendEmail(email: String?): Boolean {
    return email?.run {
        if (isNotEmpty()) {
            // send email
            true
        } else {
            false
        }
    } ?: false
}

Enter fullscreen mode Exit fullscreen mode

In this example, we use the run function to perform a null check on the email parameter. If email is not null, we proceed to check if it is empty. If it is not empty, we send the email and return true. If it is empty, or if email is null, we return false. This allows us to avoid having to write separate null and empty check logic, which makes our code more concise and easier to read.

4. Apply

The apply function is a useful utility function in Kotlin that allows you to perform a set of operations on an object and return the object itself. This can be particularly useful when you want to perform a series of operations on an object and then return the object for further processing.

To use the apply function, you call it on an object and pass a lambda expression as an argument. The lambda expression is executed on the object and has access to the object's properties and methods. When the lambda expression finishes executing, the apply function returns the object.

Here's an example of how you might use the apply function to initialize an object:

val person = Person().apply {
    name = "John"
    age = 30
    address = "123 Main St"
}

Enter fullscreen mode Exit fullscreen mode

In this example, apply is called on a new instance of Person, and the lambda expression sets the name, age, and address properties of the Person object. When the lambda expression finishes executing, the apply function returns the Person object.

You can also use the apply function to perform a series of operations on an object and then return the object for further processing. For example:

val result = person.apply {
    name = "John Smith"
    age = 35
}.apply {
    address = "456 Main St"
}.apply {
    phone = "123-456-7890"
}

Enter fullscreen mode Exit fullscreen mode

In this example, the apply function is called on the person object three times, each time performing a set of operations on the object and returning the object for further processing. This can be a convenient way to perform a series of operations on an object without having to write a lot of boilerplate code.

Overall, the apply function is a useful utility function in Kotlin that allows you to perform a set of operations on an object and return the object itself. It can help you write concise and expressive code, particularly when you need to perform a series of operations on an object and then return the object for further processing.

5. With

The with function is a utility function in Kotlin that allows you to perform a set of operations on an object and return a result. It's similar to the apply function, but instead of returning the object itself, it returns the result of the lambda expression that you pass to it.

To use the with function, you call it on an object and pass a lambda expression as an argument. The lambda expression is executed on the object and has access to the object's properties and methods. When the lambda expression finishes executing, the with function returns the result of the lambda expression.

Here's an example of how you might use the with function to perform a set of operations on an object and return a result:

val result = with(person) {
    name = "John Smith"
    age = 35
    "Name: $name, Age: $age"
}

Enter fullscreen mode Exit fullscreen mode

In this example, the with function is called on the person object, and the lambda expression performs a set of operations on the object (setting the name and age properties) and returns a string containing the name and age of the person object. The with function returns the result of the lambda expression, which is the string "Name: John Smith, Age: 35".

You can also use the with function to perform a series of operations on multiple objects and return a result. For example:

val result = with(person) {
    name = "John Smith"
    age = 35
}.with(address) {
    street = "456 Main St"
    city = "New York"
    state = "NY"
    "Address: $street, $city, $state"
}
Enter fullscreen mode Exit fullscreen mode

In this example, the with function is called on the person object and the address object, and the lambda expressions perform a set of operations on each object and return a string containing the street, city, and state of the address object. The with function returns the result of the second lambda expression, which is the string "Address: 456 Main St, New York, NY".

Overall, the with function is a useful utility function in Kotlin that allows you to perform a set of operations on an object and return a result. It can help you write concise and expressive code, particularly when you need to perform a series of operations on an object and then return a result.

Summary

In conclusion, the let function is a useful tool in Kotlin that allows you to perform a block of code on an object, and then return the object itself. It is particularly useful for performing null checks and chaining operations together. By using the let function, you can write cleaner and more readable code in Kotlin.

Top comments (0)