1. Introduction

Kotlin offers a rich set of features to make our code expressive and readable. Two of the frequently used keywords in Kotlin, it and this, may appear to be quite similar at first glance. However, understanding the differences between them can greatly enhance our programming skills and help us write more maintainable code.

In this tutorial, we’ll discuss the differences between the it and this keywords in Kotlin, and their use cases in different contexts.

2. The it Keyword in Kotlin

Kotlin uses the it keyword as an implicit name for single-parameter lambda expressions or anonymous functions. It simplifies the syntax for these expressions by eliminating the need to explicitly declare a name for that parameter:

fun addOne(numbers: List<Int>): List<Int> {
    return numbers.map{ it + 1 }
}

In this code, we have a function called addOne() that takes a list of integer numbers as a parameter and returns a new list of integers. The map() function performs the transformation. In the map() function, we have a lambda expression where we use it to represent each element of the numbers list as we iterate over it. So, the lambda adds one to each element of the numbers list.

Let’s take a look at how we can test our code with JUnit:

@Test
fun testAddOne() {
    val inputNumbers = listOf(1, 2, 3, 4, 5)
    val result = addOne(inputNumbers)
    val expected = listOf(2, 3, 4, 5, 6)
    assertEquals(expected, result)
}

3. The this Keyword in Kotlin

In Kotlin, this is used to refer to the current instance of a class. It plays a similar role to this in other programming languages, such as Java. The keyword is used within class methods to access instance variables and methods:

data class Person(val name: String) {
    // An instance variable
    var age: Int = 0
    fun haveBirthday() {
        this.age++
    }
}

The this keyword explicitly references the current instance of Person in haveBirthday() to increment their age.

Finally, we’ll test the haveBirthday() function:

@Test
fun testHaveBirthday() {
    val person = Person("Bob")
    person.haveBirthday()
    assertEquals(1, person.age)
}

4. Use Cases of this Keyword

In this section, we’ll explore several additional ways to utilize Kotlin’s this keyword.

4.1. Extension Function

When defining extension functions, we can use this to refer to the object reference the extension function is called on:

fun String.customLength(): Int {
    return this.length
}
val length = "Hello, Kotlin".customLength()

Let’s verify our customLength() extension function:

@Test
fun testCustomLength() {
    val input = "Hello, Kotlin"
    val expectedLength = 13
    val actualLength = input.customLength()
    assertEquals(expectedLength, actualLength)
}

4.2. Constructor Chaining

When we have secondary constructors in a class, we must use this to call the primary constructor within the same class:

data class PersonData(val name: String, val age: Int) {
    constructor(name: String) : this(name, 0)
}

Here, we have a PersonData data class with two constructors. We can instantiate this class with name and age using the primary constructor, or with just name using the secondary constructor. By using the secondary constructor, age defaults to zero from the internal usage of the primary constructor. The this keyword references the primary constructor from the secondary constructor.

Let’s see how we can test our secondary constructor:

@Test
fun testSecondaryConstructor() {
    val person = PersonData("Alice")
    assertEquals("Alice", person.name)
    assertEquals(0, person.age)
}

5. Key Differences Between the it and this Keywords

Finally, let’s consider some key differences between these keywords that we should be aware of.

The it keyword is used as an implicit name for a single parameter in a lambda expression or an anonymous function. It allows us to refer to the single parameter of a lambda function without needing to explicitly name it.

Conversely, the this keyword refers to the current instance of an object reference, within a class or extension function. It accesses instance members, properties, and functions within a class or extension function to differentiate between instance members and local variables or parameters with the same name.

6. Conclusion

The it keyword simplifies lambda expressions with a single parameter. On the other hand, the this keyword is a reference to the current instance within a class and is used to access instance variables and methods.

As always, the full implementation of these examples is available over on GitHub.

Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.