Kotlin 'also' scope function examples

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)
    myList.also{println("$myList")}    
}

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)
    myList.also{println("$it")}    
}

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)
    
    myList
    .also{println("Adding a new value")}
    .add(6)
    .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}")}
    println("$alex")
}

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.

Where is the color and why codevscolor ?

Long story short, I love paintings and I paint on weekends. We(me and my wife) have one Youtube channel. Below is a video that I did recently. If you love this please do subscribe to support us 😊