Complete the code to print the name using 'this' receiver inside the class.
class Person(val name: String) { fun printName() { println([1].name) } } fun main() { val p = Person("Anna") p.printName() }
In Kotlin, this refers to the current object instance inside a class.
Complete the lambda expression to print the name using the implicit 'it' receiver.
val names = listOf("Anna", "Bob") names.forEach { [1] -> println([1]) }
In a lambda with explicit parameter, you name the parameter (here 'name') and use it inside.
Fix the error by choosing the correct receiver to access the property inside the lambda with receiver.
class Person(val name: String) { fun greet() { val printName = with(this) { { println([1].name) } } printName() } } fun main() { val p = Person("Anna") p.greet() }
Inside 'with(this)', 'this' refers to the Person object, so use 'this.name'.
Fill both blanks to correctly use 'this' and 'it' in nested lambdas.
class Person(val name: String) { fun greetAll(names: List<String>) { names.forEach [1] -> println("Hello, $[2]!") } } fun main() { val p = Person("Anna") p.greetAll(listOf("Bob", "Carol")) }
In forEach, the lambda parameter is 'it' by default, representing each name. Inside the string, we use 'name' from the lambda parameter.
Fill all three blanks to correctly use 'this' and 'it' in a nested scope with 'apply' and 'let'.
class Person(var greeting: String) { fun greet(name: String) { this.apply { greeting = "Hello" name.let [1] -> println("$[2], $[3]!") } } } fun main() { val p = Person("") p.greet("Bob") }
Inside 'let', 'it' is the lambda parameter (the name). Inside 'apply', 'this' refers to the Person object, so use 'this.greeting'.