Complete the code to create an instance of a StringBuilder and append text using a scope function.
val result = StringBuilder().[1] { append("Hello") append(" World") }.toString()
The apply function allows you to configure an object within its scope and returns the object itself, reducing boilerplate when initializing.
Complete the code to safely access the length of a nullable string using a scope function.
val length = nullableString?.[1] { length } ?: 0
The let function is useful for executing code only if the object is not null and returns the lambda result.
Fix the error in the code by choosing the correct scope function to execute a block and return its result.
val result = "Hello".[1] { this.length }
The run function executes the block with the object as receiver and returns the lambda result, suitable here to get the length.
Fill both blanks to create a mutable list and add elements using scope functions.
val list = mutableListOf<Int>().[1] { add(1) add(2) }.[2] { println("List size: $size") }
apply is used to configure the list by adding elements, returning the list itself. also is used to perform an additional action (printing) without changing the list.
Fill all three blanks to filter a list and create a map of word lengths using scope functions.
val words = listOf("apple", "banana", "cherry") val lengths = words.filter { it.length [1] 5 }.[2] { associateWith { it.length [3] 0 } }
The filter uses > to select words longer than 5. The let function is used to transform the filtered list. The Elvis operator ?: provides a default value if length is null (though length is non-null here, it's used illustratively).