Bird
0
0

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 }
Bfun transformList(nums: List<Int>, transformer: Int): List<Int> { return nums.map { transformer } }
Cfun transformList(nums: List<Int>): List<Int> { return nums.map { it * 2 } }
Dfun transformList(nums: List<Int>, transformer: (Int) -> Int): List<Int> { nums.forEach { transformer(it) } return nums }
Step-by-Step Solution
Solution:
  1. Step 1: Understand the requirement

    The function must accept a list and a function to transform each element, returning a new list with transformed values.
  2. 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.
  3. 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 }
  4. 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

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes