0
0
Kotlinprogramming~10 mins

Why scope functions reduce boilerplate in Kotlin - Test Your Understanding

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

Complete the code to create an instance of a StringBuilder and append text using a scope function.

Kotlin
val result = StringBuilder().[1] {
    append("Hello")
    append(" World")
}.toString()
Drag options to blanks, or click blank then click option'
Aapply
Balso
Crun
Dlet
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'let' returns the lambda result, not the object itself.
2fill in blank
medium

Complete the code to safely access the length of a nullable string using a scope function.

Kotlin
val length = nullableString?.[1] {
    length
} ?: 0
Drag options to blanks, or click blank then click option'
Aapply
Blet
Crun
Dalso
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'apply' returns the object, not the lambda result.
3fill in blank
hard

Fix the error in the code by choosing the correct scope function to execute a block and return its result.

Kotlin
val result = "Hello".[1] {
    this.length
}
Drag options to blanks, or click blank then click option'
Aapply
Balso
Cwith
Drun
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'apply' returns the object, not the lambda result.
4fill in blank
hard

Fill both blanks to create a mutable list and add elements using scope functions.

Kotlin
val list = mutableListOf<Int>().[1] {
    add(1)
    add(2)
}.[2] {
    println("List size: $size")
}
Drag options to blanks, or click blank then click option'
Aapply
Blet
Calso
Drun
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'let' for the first blank returns the lambda result, not the list.
5fill in blank
hard

Fill all three blanks to filter a list and create a map of word lengths using scope functions.

Kotlin
val words = listOf("apple", "banana", "cherry")
val lengths = words.filter { it.length [1] 5 }.[2] {
    associateWith { it.length [3] 0 }
}
Drag options to blanks, or click blank then click option'
A>
Bapply
C?:
Dlet
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'apply' instead of 'let' for the second blank returns the object, not the transformed result.