0
0
Kotlinprogramming~3 mins

This vs it receiver difference in Kotlin - When to Use Which

Choose your learning style9 modes available
The Big Idea

Discover how two tiny words can make your Kotlin code cleaner and less confusing!

The Scenario

Imagine you are trying to write a program that works with objects and their properties. You want to run some code inside the object, but you have to keep repeating the object name everywhere. It feels like writing the full address every time you want to visit a room in your house.

The Problem

Manually repeating the object name makes your code long and hard to read. It's easy to make mistakes by typing the wrong name or forgetting it. This slows you down and makes your program confusing, like giving directions with too many details.

The Solution

Kotlin's this and it keywords act like shortcuts. this refers to the current object, so you don't have to say its name again. it is a default name for a single parameter in lambdas, making your code cleaner and easier to understand.

Before vs After
Before
val person = Person()
person.run {
    println(person.name)
}
After
val person = Person()
person.run {
    println(this.name)
}

listOf(1, 2, 3).forEach {
    println(it)
}
What It Enables

It lets you write shorter, clearer code that focuses on what matters, without repeating object names or parameters.

Real Life Example

When you want to print all names in a list, using it lets you quickly access each item without extra code. When working inside an object, this helps you refer to its properties easily.

Key Takeaways

this refers to the current object inside its scope.

it is the default name for a single lambda parameter.

Both help reduce repetition and make code easier to read.