0
0
Kotlinprogramming~30 mins

Returning functions from functions in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Returning functions from functions
📖 Scenario: Imagine you are creating a simple calculator app. You want to create different operations like addition and multiplication. Instead of writing separate functions for each operation, you will write a function that returns another function based on the operation you want.
🎯 Goal: Build a Kotlin program where a function returns another function that performs a math operation. You will create a function that returns either an addition or multiplication function based on a given input.
📋 What You'll Learn
Create a function called getOperation that takes a String parameter called operation.
Inside getOperation, return a function that takes two Int parameters and returns an Int.
If operation is "add", return a function that adds two numbers.
If operation is "multiply", return a function that multiplies two numbers.
Call getOperation with "add" and "multiply" and print the results of calling the returned functions with numbers 5 and 3.
💡 Why This Matters
🌍 Real World
Returning functions from functions is useful in apps that need flexible behavior, like calculators, games, or event handlers.
💼 Career
Understanding how to return functions helps in writing clean, reusable, and flexible code, a skill valued in software development jobs.
Progress0 / 4 steps
1
Create the getOperation function skeleton
Write a function called getOperation that takes a String parameter named operation and returns a function type that takes two Int parameters and returns an Int. For now, return a function that adds two numbers.
Kotlin
Need a hint?

Remember, the function getOperation should return another function that takes two integers and returns their sum.

2
Add condition to return different functions
Inside the getOperation function, add an if statement to check if operation is "add". If yes, return a function that adds two numbers. Otherwise, return a function that multiplies two numbers.
Kotlin
Need a hint?

Use an if statement to check the operation string and return the correct function.

3
Call getOperation and use returned functions
Create two variables called addFunc and multiplyFunc. Assign them the result of calling getOperation with "add" and "multiply" respectively. Then call each function with arguments 5 and 3 and store the results in sumResult and productResult.
Kotlin
Need a hint?

Call getOperation with the correct strings and then call the returned functions with 5 and 3.

4
Print the results
Write two println statements to print sumResult and productResult.
Kotlin
Need a hint?

Use println to show the results on the screen.