Complete the code to run the block and return its result.
val result = run [1] { 5 + 3 } println(result)
The run function takes a lambda with no parameters and returns the lambda's result. The lambda type is () -> Int here.
Complete the code to run a block on a nullable object safely.
val name: String? = "Kotlin" val length = name?.run [1] { length } ?: 0 println(length)
run on an object.?: 0.The run function called on an object uses the object as this inside the lambda, which takes no parameters. The lambda returns the length of the string.
Fix the error in the run block to correctly return the last character.
val word = "hello" val lastChar = run [1] { word[word.length] } println(lastChar)
The lambda returns a Char and has no parameters. The index should be word.length - 1 to avoid an error, but the blank is for the lambda type.
Fill both blanks to create a map of words to their lengths using run.
val words = listOf("apple", "banana", "cherry") val lengths = words.associateWith [1] { it.[2] } println(lengths)
count or size instead of length for strings.run in the first blank.The associateWith function takes a lambda that returns a value for each element. Using run runs the block on each word, and length gets the word's length.
Fill all three blanks to filter and map words using run with conditions.
val words = listOf("dog", "cat", "elephant", "fox") val filtered = words.filter [1] { it.length [2] 3 }.map [3] { it.uppercase() } println(filtered)
filter or map as the lambda instead of run.The filter function takes a lambda to select words longer than 3. Using run runs the lambda on each word. Then map transforms each word to uppercase using run.