📖 Scenario: Imagine you are organizing a music playlist app. You want to create different ways to play songs, like playing normally, shuffling, or repeating. You will use functions as values to switch between these play modes easily.
🎯 Goal: Build a Kotlin program that shows how functions can be stored in variables, passed as arguments, and returned from other functions. This will demonstrate why functions are first-class citizens in Kotlin.
📋 What You'll Learn
Create a function variable that holds a function to play a song normally
Create a function variable that holds a function to play a song shuffled
Create a function that takes a function as a parameter and calls it
Create a function that returns a function to repeat a song
Call these functions and print the results
💡 Why This Matters
🌍 Real World
Using functions as values helps build flexible apps like music players, where you can change behavior easily without rewriting code.
💼 Career
Understanding first-class functions is key for Kotlin developers to write clean, reusable, and functional-style code in real projects.
Progress0 / 4 steps
1
Create function variables for play modes
Create two function variables called playNormal and playShuffle. Each should be a function that takes a String parameter called song and returns a String. playNormal should return the string "Playing {song} normally" using an f-string style. playShuffle should return "Playing {song} shuffled" similarly.
Kotlin
Hint
Use lambda expressions to assign functions to variables. The syntax is val name: (ParameterType) -> ReturnType = { parameter -> expression }.
2
Create a function that takes a function parameter
Create a function called playSong that takes two parameters: a String called song and a function called playMode of type (String) -> String. The function should return the result of calling playMode(song).
Kotlin
Hint
Define a function with a function parameter by specifying the parameter type as (String) -> String. Then call it inside the function.
3
Create a function that returns a function
Create a function called repeatPlay that takes no parameters and returns a function of type (String) -> String. The returned function should take a song string and return "Repeating {song}...".
Kotlin
Hint
Return a lambda function from a function by specifying the return type as (String) -> String and returning a lambda.
4
Call the functions and print the results
Call playSong with the song "Hello" and the function playNormal. Then call playSong with the song "World" and the function playShuffle. Then call repeatPlay() to get a function, and call that function with the song "Hello". Print all three results each on its own line.
Kotlin
Hint
Use println to print each result. Call repeatPlay() to get the function, then call it with a song.
Practice
(1/5)
1. Which of the following best explains why functions are considered first-class citizens in Kotlin?
easy
A. Because functions must always return a value.
B. Because functions cannot be nested inside other functions.
C. Because functions can be stored in variables, passed as arguments, and returned from other functions.
D. Because functions are only used for input/output operations.
Solution
Step 1: Understand the meaning of first-class functions
First-class functions means functions can be treated like any other value: stored, passed, and returned.
Step 2: Match this meaning with the options
Because functions can be stored in variables, passed as arguments, and returned from other functions. correctly states this ability, while others describe unrelated or incorrect facts.
Final Answer:
Because functions can be stored in variables, passed as arguments, and returned from other functions. -> Option C
Quick Check:
First-class functions = store, pass, return [OK]
Hint: Remember: first-class means functions act like variables [OK]
Common Mistakes:
Thinking functions must always return a value
Believing functions cannot be nested
Confusing first-class with input/output only
2. Which of the following is the correct syntax to assign a lambda function to a variable in Kotlin?
val greet = () -> println("Hello") matches the correct lambda syntax. val greet = fun() { println("Hello") } is a named function expression, B and D are invalid syntax.
Final Answer:
val greet = () -> println("Hello") -> Option D
Quick Check:
Lambda syntax = () -> expression [OK]
Hint: Look for arrow notation () -> for lambdas [OK]
Common Mistakes:
Using 'function()' keyword which doesn't exist
Confusing named function with lambda syntax
Using 'lambda' keyword which is invalid
3. What will be the output of the following Kotlin code?
fun operate(x: Int, y: Int, op: (Int, Int) -> Int): Int {
return op(x, y)
}
fun main() {
val sum = operate(5, 3) { a, b -> a + b }
println(sum)
}
medium
A. 8
B. 53
C. Error: Missing function body
D. 0
Solution
Step 1: Understand the operate function
It takes two Ints and a function 'op' that combines them, then returns the result of op(x, y).
Step 2: Analyze the lambda passed
The lambda { a, b -> a + b } adds the two numbers 5 and 3, so operate returns 8.
Final Answer:
8 -> Option A
Quick Check:
5 + 3 = 8 [OK]
Hint: Trace lambda execution with given inputs [OK]
Common Mistakes:
Concatenating numbers as strings instead of adding
Expecting syntax error due to lambda
Ignoring the lambda parameter and outputting 0
4. Identify the error in the following Kotlin code that uses a function as a parameter:
fun applyOperation(x: Int, y: Int, operation: (Int, Int) -> Int): Int {
return operation(x, y)
}
fun main() {
val result = applyOperation(4, 2) { a, b -> a * b
println(result)
}
medium
A. Incorrect function parameter types.
B. Missing closing brace '}' for the lambda expression.
C. applyOperation should return Unit, not Int.
D. Lambda parameters must be declared outside the function call.
Solution
Step 1: Check lambda syntax in main()
The lambda passed to applyOperation lacks a closing brace '}', causing a syntax error.
Step 2: Verify other parts
Parameter types and return types are correct; lambda parameters inside call are valid.
Final Answer:
Missing closing brace '}' for the lambda expression. -> Option B
Quick Check:
Unclosed lambda = syntax error [OK]
Hint: Count opening and closing braces in lambdas [OK]
Common Mistakes:
Assuming parameter types are wrong
Thinking return type must be Unit
Believing lambda parameters can't be inline
5. 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?
hard
A. fun transformList(nums: List<Int>, transformer: (Int) -> Int): List<Int> {
val result = mutableListOf<Int>()
for (num in nums) {
result.add(transformer(num))
}
return result
}
B. fun transformList(nums: List<Int>, transformer: Int): List<Int> {
return nums.map { transformer }
}
C. fun transformList(nums: List<Int>): List<Int> {
return nums.map { it * 2 }
}
D. fun transformList(nums: List<Int>, transformer: (Int) -> Int): List<Int> {
nums.forEach { transformer(it) }
return nums
}
Solution
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.
Step 2: Analyze each option
fun transformList(nums: List<Int>, transformer: (Int) -> Int): List<Int> {
val result = mutableListOf<Int>()
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<Int>, transformer: Int): List<Int> {
return nums.map { transformer }
} wrongly treats transformer as Int. fun transformList(nums: List<Int>): List<Int> {
return nums.map { it * 2 }
} lacks a transformer parameter. fun transformList(nums: List<Int>, transformer: (Int) -> Int): List<Int> {
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<Int>, transformer: (Int) -> Int): List<Int> {
val result = mutableListOf<Int>()
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]
Hint: Look for function parameter applied to each element and new list returned [OK]
Common Mistakes:
Passing transformer as Int instead of function
Not returning a new transformed list
Using forEach without collecting results
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.