Bird
0
0

Which of the following implementations correctly uses a local function to achieve this?

hard📝 Application Q15 of 15
Kotlin - Functions
You want to write a Kotlin function processNumbers that takes a list of integers and returns the sum of their squares. You decide to use a local function square inside it. Which of the following implementations correctly uses a local function to achieve this?
Afun processNumbers(nums: List<Int>): Int { fun square(x: Int) = x * x var sum = 0 for (n in nums) { sum += n } return sum }
Bfun processNumbers(nums: List<Int>): Int { var sum = 0 for (n in nums) { fun square(x: Int) = x * x sum += square } return sum }
Cfun processNumbers(nums: List<Int>): Int { fun square(x: Int) = x * x return nums.map square(it).sum() }
Dfun processNumbers(nums: List<Int>): Int { fun square(x: Int) = x * x return nums.sumOf { square(it) } }
Step-by-Step Solution
Solution:
  1. Step 1: Understand local function usage and Kotlin collection functions

    Local function 'square' should be declared once inside 'processNumbers'. Using Kotlin's 'sumOf' is concise and correct.
  2. Step 2: Analyze each option

    fun processNumbers(nums: List): Int { fun square(x: Int) = x * x return nums.sumOf { square(it) } } correctly declares the local function once and uses it with sumOf { square(it) }.
    fun processNumbers(nums: List): Int { var sum = 0 for (n in nums) { fun square(x: Int) = x * x sum += square } return sum } declares 'square' inside the loop but calls it without argument square(n), compile error.
    fun processNumbers(nums: List): Int { fun square(x: Int) = x * x return nums.map square(it).sum() } has syntax error: nums.map square(it).sum() missing lambda braces {}.
    fun processNumbers(nums: List): Int { fun square(x: Int) = x * x var sum = 0 for (n in nums) { sum += n } return sum } defines 'square' but uses sum += n, computes sum of numbers not squares.
  3. Final Answer:

    fun processNumbers(nums: List): Int { fun square(x: Int) = x * x return nums.sumOf { square(it) } } -> Option D
  4. Quick Check:

    Local function + sumOf = fun processNumbers(nums: List): Int { fun square(x: Int) = x * x return nums.sumOf { square(it) } } [OK]
Quick Trick: Declare local function once; use sumOf for concise sum [OK]
Common Mistakes:
MISTAKES
  • Calling local function without required arguments
  • Syntax error: missing braces in lambda expression
  • Defining local function but forgetting to use it

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes