Which of the following implementations correctly uses first-class functions to achieve this?
hard📝 Application Q15 of 15
Kotlin - Functions
You want to create a Kotlin function that takes a list of integers and a function to transform each integer, returning a new list with transformed values. Which of the following implementations correctly uses first-class functions to achieve this?
Afun transformList(nums: List<Int>, transformer: (Int) -> Int): List<Int> {
val result = mutableListOf<Int>()
for (num in nums) {
result.add(transformer(num))
}
return result
}
The function must accept a list and a function to transform each element, returning a new list with transformed values.
Step 2: Analyze each option
fun transformList(nums: List, transformer: (Int) -> Int): List {
val result = mutableListOf()
for (num in nums) {
result.add(transformer(num))
}
return result
} correctly takes a function parameter and applies it to each element, collecting results in a new list. fun transformList(nums: List, transformer: Int): List {
return nums.map { transformer }
} wrongly treats transformer as Int. fun transformList(nums: List): List {
return nums.map { it * 2 }
} lacks a transformer parameter. fun transformList(nums: List, transformer: (Int) -> Int): List {
nums.forEach { transformer(it) }
return nums
} applies transformer but returns original list without changes.
Final Answer:
fun transformList(nums: List<Int>, transformer: (Int) -> Int): List<Int> {
val result = mutableListOf<Int>()
for (num in nums) {
result.add(transformer(num))
}
return result
} -> fun transformList(nums: List, transformer: (Int) -> Int): List {
val result = mutableListOf()
for (num in nums) {
result.add(transformer(num))
}
return result
}
Quick Check:
Function parameter + new list = fun transformList(nums: List<Int>, transformer: (Int) -> Int): List<Int> {
val result = mutableListOf<Int>()
for (num in nums) {
result.add(transformer(num))
}
return result
} [OK]
Quick Trick:Look for function parameter applied to each element and new list returned [OK]
Common Mistakes:
MISTAKES
Passing transformer as Int instead of function
Not returning a new transformed list
Using forEach without collecting results
Master "Functions" in Kotlin
9 interactive learning modes - each teaches the same concept differently