class Example { fun printThis() { val numbers = listOf(1, 2, 3) numbers.forEach { println("it: $it") } numbers.forEach { number -> println("number: $number") } } } fun main() { val example = Example() example.printThis() }
In Kotlin, inside a lambda with one parameter, 'it' refers to that parameter implicitly. When you name the parameter explicitly (like 'number'), you use that name instead of 'it'. 'this' refers to the instance of the enclosing class, not the lambda parameter.
'this' inside a lambda with receiver refers to the receiver object of the lambda. 'it' is the implicit name of the single parameter passed to a lambda without an explicit parameter name.
class Outer { val name = "Outer" fun run() { val inner = Inner() inner.action { println(this.name) println(it) } } inner class Inner { val name = "Inner" fun action(block: Inner.(String) -> Unit) { this.block("Parameter") } } } fun main() { val outer = Outer() outer.run() }
The lambda is an extension function on Inner, so 'this' refers to the Inner instance. 'it' is the single parameter passed to the lambda, which is the string "Parameter".
fun main() { val list = listOf(1, 2, 3) list.forEach { println(this) } }
Inside a lambda without a receiver, 'this' refers to the enclosing class or function. In this case, 'main' is a top-level function, so 'this' is not defined, causing an unresolved reference error.
class Greeter(val greeting: String) { fun greet() { val printGreeting: Greeter.(String) -> Unit = { println("$greeting, $it!") } this.printGreeting("World") } } fun main() { val greeter = Greeter("Hello") greeter.greet() }
The lambda 'printGreeting' is an extension function on Greeter with a single String parameter. Inside it, 'greeting' is accessed via 'this' (the Greeter instance), and 'it' is the parameter passed when calling the lambda.