Complete the code to calculate the sum of all numbers in the list using fold.
val numbers = listOf(1, 2, 3, 4) val sum = numbers.fold([1]) { acc, num -> acc + num } println(sum)
The fold function starts with an initial value. For summing numbers, the initial value should be 0.
Complete the code to find the product of all numbers in the list using reduce.
val numbers = listOf(2, 3, 4) val product = numbers.reduce { acc, num -> acc [1] num } println(product)
The reduce function combines elements. To get the product, use the multiplication operator '*'.
Fix the error in the code to correctly concatenate all strings in the list using fold.
val words = listOf("Kotlin", "is", "fun") val sentence = words.fold([1]) { acc, word -> acc + " " + word } println(sentence.trim())
For string concatenation, the fold initial value should be an empty string "".
Fill both blanks to create a map of words to their lengths, but only include words longer than 3 characters.
val words = listOf("apple", "bat", "carrot", "dog") val lengths = words.associateWith { [1] } val filtered = lengths.filter { it.value [2] 3 } println(filtered)
Use it.length to get the length of each word. Filter words with length greater than 3 using '>'.
Fill all three blanks to create a map of uppercase words to their lengths, including only words longer than 4 characters.
val words = listOf("tree", "house", "car", "elephant") val result = words.filter { it.length [1] 4 } .associateBy([2]) { [3] } println(result)
Filter words with length greater than 4 using '>'. Use it.uppercase() as the key and it.length as the value in associateBy.