Discover how two tiny words can make your Kotlin code cleaner and less confusing!
This vs it receiver difference in Kotlin - When to Use Which
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.
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.
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.
val person = Person()
person.run {
println(person.name)
}val person = Person()
person.run {
println(this.name)
}
listOf(1, 2, 3).forEach {
println(it)
}It lets you write shorter, clearer code that focuses on what matters, without repeating object names or parameters.
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.
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.