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.
0
0
This vs it receiver difference in Kotlin
Introduction
When you want to access the current object inside a class or function, use <code>this</code>.
When you use a lambda with one parameter and want a short name for it, use <code>it</code>.
When you want to call methods or properties on an object inside a <code>with</code> or <code>apply</code> block, use <code>this</code>.
When you want to refer to the single parameter of a lambda without naming it, use <code>it</code>.
Syntax
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.
Examples
Here,
it is each item in the list during the loop.Kotlin
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.Kotlin
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.Kotlin
val result = with("hello") { println(this.uppercase()) // 'this' is the string "hello" length }
it is used as the default name for the lambda parameter.Kotlin
val doubled = listOf(1, 2, 3).map { it * 2 // 'it' is each number }
Sample Program
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.
Kotlin
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() }
OutputSuccess
Important Notes
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.
Summary
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.