Complete the code to use the also function to print the number before returning it.
fun printNumber(num: Int): Int {
return num.[1] {
println("Number is: $it")
}
}apply which returns the object but uses this instead of it.let which returns the lambda result, not the original object.The also function lets you perform an action with the object (here, num) and then returns the original object. This is perfect for printing and returning the same value.
Complete the code to add an element to the list and print the updated list using also.
val numbers = mutableListOf(1, 2, 3) numbers.[1](4).also { println("Updated list: $numbers") }
apply which expects this and is used for configuring objects.let which returns the lambda result, not the original object.also is used here to perform an action (printing) after adding an element, while returning the original result of add.
Fix the error in the code by choosing the correct function to chain calls and print the object.
val text = "Hello" val result = text.[1] { println(it) }.uppercase()
run which returns the lambda result, breaking the chain.apply which uses this and may confuse chaining.also returns the original object, so uppercase() can be called on the string. apply returns the object but uses this, run returns the lambda result, and with is not called as an extension.
Fill both blanks to create a mutable list, add an element, and print the list using also.
val list = mutableListOf(1, 2, 3).[1] { this.add(4) }.[2] { println(it) }
let which returns the lambda result, not the object.run which returns the lambda result.apply is used to add an element because it uses this and returns the object. Then also is used to print the list and return it.
Fill all three blanks to create a string, print it, convert to uppercase, and print again using also.
val message = "hello".[1] { println("Original: $it") }.[2]().[3] { println("Uppercase: $it") }
let which changes the return value and breaks chaining.apply which uses this and is less clear here.also is used to print the original string, then uppercase() converts it, and also prints the uppercase string. This keeps the original object flowing through the chain.