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.
Practice
this refer to inside a class method?Solution
Step 1: Understand
Inside a class method,thisin class contextthisrefers to the current object instance that called the method.Step 2: Differentiate from lambda parameter
thisis not a lambda parameter; that role is usually played byitin single-parameter lambdas.Final Answer:
The current instance of the class -> Option AQuick Check:
thisin class = current object [OK]
this means current object in classes [OK]- Confusing
thiswith lambda parameterit - Thinking
thisis a global variable - Assuming
thisrefers to static context
Solution
Step 1: Identify default lambda parameter
In Kotlin, when a lambda has a single parameter and no explicit name, it is referred to asit.Step 2: Confirm
thisis not used herethisrefers to the receiver object, not the lambda parameter.Final Answer:
it -> Option BQuick Check:
Single lambda parameter =it[OK]
it [OK]- Using
thisinstead ofitin lambdas - Trying to name the parameter without declaration
- Assuming
selfis valid in Kotlin
class Box(val value: Int) {
fun printValue() {
listOf(1).forEach {
println(this.value + it)
}
}
}
fun main() {
Box(5).printValue()
}Solution
Step 1: Understand
Insidethisinside lambda with receiverprintValue,thisrefers to theBoxinstance, sothis.valueis 5.Step 2: Calculate the sum inside lambda
The lambda parameteritis 1 from the list. So,this.value + it = 5 + 1 = 6.Final Answer:
6 -> Option AQuick Check:
this.value + it= 6 [OK]
this is outer object, it is lambda param [OK]- Thinking
thisrefers to lambda receiver - Confusing
itwiththis - Expecting compilation error due to
thisusage
fun main() {
val numbers = listOf(1, 2, 3)
numbers.forEach {
println(this + it)
}
}Solution
Step 1: Check
In this lambda, there is no receiver object, sothisusage inside lambdathisis not defined and causes an error.Step 2: Confirm lambda parameter usage
itis valid as the lambda parameter, butthiscannot be used without a receiver context.Final Answer:
Usingthisinside lambda without receiver causes error -> Option CQuick Check:
thisneeds receiver, else error [OK]
this inside lambda [OK]- Assuming
thisalways refers to lambda parameter - Ignoring that
thisrequires receiver context - Thinking code runs without error
class Calculator {
fun calculate() {
val numbers = listOf(10, 20)
numbers.run {
println(this.sum())
numbers.forEach {
println(it + this.sum())
}
}
}
}
fun main() {
Calculator().calculate()
}Solution
Step 1: Understand
Insidethisinsiderunblockrun,thisrefers to thenumberslist. So,this.sum()is 30.Step 2: Calculate outputs inside
For eachforEachitinnumbers(10 and 20), printit + this.sum(): 10+30=40 and 20+30=50.Step 3: List all printed lines
First print: 30
Then prints: 40 and 50Final Answer:
30 40 50 -> Option DQuick Check:
thisinrun= list, sum=30 [OK]
run, this is receiver object [OK]- Confusing
thisinside nested lambdas - Assuming
thisrefers to Calculator instance - Expecting compilation error due to
this
Ready to prove it?
Pass the test and this pattern moves unknown
