0
0
Kotlinprogramming~15 mins

Local functions (nested functions) in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Local Functions in Kotlin
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Use println(total) to show the total price.