0
0
Kotlinprogramming~20 mins

Passing lambdas to functions in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Passing lambdas to functions
📖 Scenario: Imagine you are building a simple calculator app that can perform different operations on numbers. You want to write a function that takes two numbers and a small piece of code (a lambda) that tells it what operation to do.
🎯 Goal: You will create a function that accepts two numbers and a lambda function to perform an operation on these numbers. Then, you will call this function with different lambdas to see different results.
📋 What You'll Learn
Create a function called calculate that takes two Int parameters named a and b, and a lambda parameter named operation of type (Int, Int) -> Int.
Create a variable called add that holds a lambda to add two numbers.
Create a variable called multiply that holds a lambda to multiply two numbers.
Call the calculate function with add and multiply lambdas and print the results.
💡 Why This Matters
🌍 Real World
Passing lambdas to functions is common in apps to customize behavior, like sorting lists or handling user actions.
💼 Career
Understanding lambdas and higher-order functions is important for Kotlin developers working on Android apps or backend services.
Progress0 / 4 steps
1
Create the calculate function
Write a function called calculate that takes two Int parameters named a and b, and a lambda parameter named operation of type (Int, Int) -> Int. The function should return the result of calling operation(a, b).
Kotlin
Need a hint?

Remember, the lambda parameter operation takes two Ints and returns an Int. Use it inside the function to get the result.

2
Create lambdas for addition and multiplication
Create a variable called add that holds a lambda to add two Int numbers. Also create a variable called multiply that holds a lambda to multiply two Int numbers.
Kotlin
Need a hint?

Use the syntax { x, y -> x + y } to create a lambda that adds two numbers.

3
Call calculate with lambdas
Call the calculate function with arguments 5 and 3 using the add lambda, and store the result in a variable called sumResult. Then call calculate with the same numbers using the multiply lambda, and store the result in a variable called productResult.
Kotlin
Need a hint?

Call calculate with 5, 3, and the lambda variable like add.

4
Print the results
Print the values of sumResult and productResult on separate lines using println.
Kotlin
Need a hint?

Use println(sumResult) and println(productResult) to show the results.