📖 Scenario: You are creating a simple program to calculate the total price of items in a shopping cart. To keep your code clean, you will use a local function inside your main function.
🎯 Goal: Build a Kotlin program that uses a local function inside main to calculate the total price of items in a shopping cart.
📋 What You'll Learn
Create a list called prices with exact values: 10, 20, 30
Create a variable called total and set it to 0
Create a local function called addPrice inside main that adds a price to total
Use a for loop to call addPrice for each price in prices
Print the value of total
💡 Why This Matters
🌍 Real World
Local functions are useful when you want to break down a task into smaller steps inside a function without making those steps visible outside. This helps keep your code clean and easier to maintain.
💼 Career
Understanding local functions is important for writing clear and efficient Kotlin code, which is valuable in Android app development and other Kotlin-based projects.
Progress0 / 4 steps
1
Create the list of prices
Create a list called prices with the exact values 10, 20, and 30 inside the main function.
Kotlin
Hint
Use val prices = listOf(10, 20, 30) to create the list.
2
Create the total variable
Inside the main function, create a variable called total and set it to 0.
Kotlin
Hint
Use var total = 0 to create a variable that can change.
3
Create the local function and loop
Inside the main function, create a local function called addPrice that takes an Int parameter called price and adds it to total. Then use a for loop with variable price to call addPrice(price) for each price in prices.
Kotlin
Hint
Define fun addPrice(price: Int) inside main. Use total += price inside it. Then loop with for (price in prices) and call addPrice(price).
4
Print the total
Add a println statement inside main to print the value of total.
Kotlin
Hint
Use println(total) to show the total price.
Practice
(1/5)
1. What is a local function in Kotlin?
easy
A. A function defined outside any class
B. A function defined inside another function
C. A function that can only return integers
D. A function that must be public
Solution
Step 1: Understand function placement
Local functions are defined inside other functions, not at the top level or in classes.
Step 2: Identify the correct definition
A function defined inside another function correctly states that a local function is inside another function, which matches Kotlin's definition.
Final Answer:
A function defined inside another function -> Option B
Quick Check:
Local function = function inside function [OK]
Hint: Local functions are nested inside other functions [OK]
Common Mistakes:
Thinking local functions are top-level
Confusing local functions with anonymous functions
Assuming local functions must be public
2. Which of the following is the correct syntax to declare a local function inside a Kotlin function?
easy
A. fun outer() { fun inner() { println("Hi") } }
B. fun outer() { def inner() { println("Hi") } }
C. fun outer() { function inner() { println("Hi") } }
D. fun outer() { inner() fun { println("Hi") } }
Solution
Step 1: Recall Kotlin function syntax
Kotlin uses the keyword 'fun' to declare functions, including local ones.
Step 2: Check each option
fun outer() { fun inner() { println("Hi") } } uses 'fun' correctly for both outer and inner functions. Others use invalid keywords or wrong order.
Final Answer:
fun outer() { fun inner() { println("Hi") } } -> Option A
Quick Check:
Local function syntax uses 'fun' keyword [OK]
Hint: Local functions use 'fun' keyword inside another function [OK]
Common Mistakes:
Using 'def' or 'function' instead of 'fun'
Placing 'fun' after the function call
Missing braces for function body
3. What will be the output of the following Kotlin code?
fun greet() {
val prefix = "Hello"
fun sayName(name: String) {
println("$prefix, $name!")
}
sayName("Alice")
}
fun main() {
greet()
}
medium
A. Hello, Alice!
B. Hello Alice!
C. Error: prefix not accessible
D. No output
Solution
Step 1: Understand variable scope in local functions
The local function 'sayName' can access 'prefix' from the outer function 'greet'.
Step 2: Trace the output of sayName("Alice")
It prints "Hello, Alice!" exactly as formatted with the comma and exclamation mark.
Final Answer:
Hello, Alice! -> Option A
Quick Check:
Local function accesses outer variable = Hello, Alice! [OK]
Hint: Local functions can use outer variables directly [OK]
Common Mistakes:
Assuming outer variables are inaccessible
Missing punctuation in output
Thinking code produces error
4. Identify the error in this Kotlin code snippet:
fun calculate() {
fun add(a: Int, b: Int): Int {
return a + b
}
}
fun main() {
println(add(3, 4))
}
medium
A. Missing return type for 'add'
B. Syntax error in function declaration
C. Cannot call local function 'add' from outside 'calculate'
D. No error, prints 7
Solution
Step 1: Understand local function visibility
The function 'add' is local inside 'calculate' and cannot be accessed outside it.
Step 2: Check where 'add' is called
'add(3, 4)' is called in 'main', outside 'calculate', causing an error.
Final Answer:
Cannot call local function 'add' from outside 'calculate' -> Option C
Quick Check:
Local functions are private to outer function [OK]
Hint: Local functions can't be called outside their outer function [OK]
Common Mistakes:
Trying to call local function from outside
Confusing local and top-level functions
Ignoring function scope rules
5. 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?
hard
A. fun processNumbers(nums: List<Int>): Int {
fun square(x: Int) = x * x
var sum = 0
for (n in nums) {
sum += n
}
return sum
}
B. fun processNumbers(nums: List<Int>): Int {
var sum = 0
for (n in nums) {
fun square(x: Int) = x * x
sum += square
}
return sum
}
C. fun processNumbers(nums: List<Int>): Int {
fun square(x: Int) = x * x
return nums.map square(it).sum()
}
D. fun processNumbers(nums: List<Int>): Int {
fun square(x: Int) = x * x
return nums.sumOf { square(it) }
}
Solution
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.
Step 2: Analyze each option
fun processNumbers(nums: List<Int>): 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>): 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>): 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>): 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.
Final Answer:
fun processNumbers(nums: List<Int>): Int {
fun square(x: Int) = x * x
return nums.sumOf { square(it) }
} -> Option D
Quick Check:
Local function + sumOf = fun processNumbers(nums: List<Int>): Int {
fun square(x: Int) = x * x
return nums.sumOf { square(it) }
} [OK]
Hint: Declare local function once; use sumOf for concise sum [OK]
Common Mistakes:
Calling local function without required arguments
Syntax error: missing braces in lambda expression
Defining local function but forgetting to use it
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.