Kotlin ‘also’ scope function examples

Published by admin on

Kotlin 'also' scope function example

Kotlin provides one scope function called also that can be used to perform some actions on an object. You can read it like also do this for it. It returns the same object and the context object is available as it. You can use it instead of the whole object.

This is a quick tutorial and I will show you a couple of different examples. Try to execute these examples and drop one comment below if you have any queries.


Example 1: With a list :

fun main(args: Array<string>) {
    val myList = mutableListOf(1,2,3,4,5)

It will print the list :

[1, 2, 3, 4, 5]

I have explained that we can access this object using it. So, the below program will print the same output :

fun main(args: Array<string>) {
    val myList = mutableListOf(1,2,3,4,5)

Again, it returns the same object. So, we can perform any other operations :

fun main(args: Array<string>) {
    val myList = mutableListOf(1,2,3,4,5)
    .also{println("Adding a new value")}
    .also({println("Final list : $myList")})    

It will print :

Adding a new value
Final list : [1, 2, 3, 4, 5, 6]

We are not using it here. It will print true because also is on the result of add, not on myList.


Example 2: Using ‘also’ with Kotlin class :

We can use also during the object creation time to print out messages. Using it, the members of an object can be accessed. For example :

fun main(args: Array<string>) {
    data class Student(var name: String, var age: Int)

    val alex = Student("Alex",20).also{println("Created one Student with : Name : ${it.name}, Age : ${it.age}")}

It will print :

Created one Student with : Name : Alex, Age : 20
Student(name=Alex, age=20)

Here, we are using also to print out one message that one Student object is created with its values. It returns the same object and assigns it to alex.

also is useful for printing debug logs. It is an easier way to access one object instead of using a new line.

Categories: kotlin


Leave a Reply

Your email address will not be published. Required fields are marked *