0
0
Kotlinprogramming~10 mins

This vs it receiver difference in Kotlin - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to print the name using 'this' receiver inside the class.

Kotlin
class Person(val name: String) {
    fun printName() {
        println([1].name)
    }
}

fun main() {
    val p = Person("Anna")
    p.printName()
}
Drag options to blanks, or click blank then click option'
Ait
Bthis
Cself
Dthat
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'it' instead of 'this' inside class methods.
2fill in blank
medium

Complete the lambda expression to print the name using the implicit 'it' receiver.

Kotlin
val names = listOf("Anna", "Bob")
names.forEach { [1] ->
    println([1])
}
Drag options to blanks, or click blank then click option'
Aname
Bit
Cthis
Dself
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'it' when parameter is explicitly named.
3fill in blank
hard

Fix the error by choosing the correct receiver to access the property inside the lambda with receiver.

Kotlin
class Person(val name: String) {
    fun greet() {
        val printName = with(this) {
            {
                println([1].name)
            }
        }
        printName()
    }
}

fun main() {
    val p = Person("Anna")
    p.greet()
}
Drag options to blanks, or click blank then click option'
Aself
Bit
Cthis
Dname
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'it' inside 'with' lambda which uses 'this' receiver.
4fill in blank
hard

Fill both blanks to correctly use 'this' and 'it' in nested lambdas.

Kotlin
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"))
}
Drag options to blanks, or click blank then click option'
Aname
Bit
Cthis.name
Dself
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'this.name' inside the lambda instead of the parameter.
5fill in blank
hard

Fill all three blanks to correctly use 'this' and 'it' in a nested scope with 'apply' and 'let'.

Kotlin
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")
}
Drag options to blanks, or click blank then click option'
Ait
Bgreeting
Dthis.greeting
Attempts:
3 left
💡 Hint
Common Mistakes
Confusing 'this' and 'it' inside nested lambdas.