We use this and it to refer to objects inside special blocks of code. They help us work with objects easily without repeating their names.
This vs it receiver difference in Kotlin
fun example() { val list = listOf(1, 2, 3) list.forEach { println(it) // 'it' is the current item } class Person { fun greet() { println(this) // 'this' is the current Person object } } }
this refers to the current object or receiver in a class or lambda with receiver.
it is the default name for a single parameter in a lambda when no name is given.
it is each item in the list during the loop.val numbers = listOf(1, 2, 3) numbers.forEach { println(it) // 'it' is each number }
this refers to the current Dog object inside the bark function.class Dog(val name: String) { fun bark() { println(this.name + " says Woof!") } } val dog = Dog("Buddy") dog.bark()
this refers to the string inside the with block.val result = with("hello") { println(this.uppercase()) // 'this' is the string "hello" length }
it is used as the default name for the lambda parameter.val doubled = listOf(1, 2, 3).map { it * 2 // 'it' is each number }
This program shows how it refers to each item in a list inside a lambda, and how this refers to the current object inside a class method.
fun main() { val names = listOf("Anna", "Bob", "Cathy") // Using 'it' in a lambda names.forEach { println("Hello, $it!") } // Using 'this' inside a class class Person(val name: String) { fun greet() { println("Hi, I am ${this.name}.") } } val person = Person("David") person.greet() }
it is only available when the lambda has exactly one parameter and you don't name it explicitly.
You can use this to clarify which object you mean if there are multiple objects in scope.
this refers to the current object or receiver.
it is the default name for a single lambda parameter.
Use this inside classes or lambdas with receivers, and it inside simple lambdas with one parameter.
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
