w3resource

Kotlin Program: Lambda expression for multiplying two numbers


Write a Kotlin program that implements a lambda expression to multiply two numbers and return the result.


Pre-Knowledge (Before You Start!)

Before solving this exercise, you should be familiar with the following concepts:

  • Lambda Expressions: A lambda expression is a short way of defining anonymous functions. In Kotlin, lambdas are enclosed in curly braces { } and can take parameters and return values.
  • Function Types: Kotlin allows you to define function types explicitly. For example, (Int, Int) -> Int represents a function that takes two integers and returns an integer.
  • Using Lambda Expressions: Lambdas can be assigned to variables and used just like regular functions.
  • Function Invocation: Once a lambda expression is stored in a variable, it can be invoked like a normal function by passing the required arguments.

Hints (Try Before Looking at the Solution!)

Here are some hints to help you solve the problem:

  • Hint 1: Declare a lambda expression that takes two integers as parameters and returns their product.
  • Hint 2: Assign the lambda expression to a variable with a function type of (Int, Int) -> Int.
  • Hint 3: Call the lambda expression by passing two integer values and store the result in a variable.
  • Hint 4: Use println() to display the result of the multiplication.

Sample Solution:

Kotlin Code:

fun main() {
    val multiply: (Int, Int) -> Int = { x, y -> x * y }

    val num1 = 7
    val num2 = 8

    val result = multiply(num1, num2)
    println("The result of multiplying $num1 and $num2 is: $result")
}

Sample Output:

The result of multiplying 7 and 8 is: 56

Explanation:

In the above exercise -

First we declare a lambda expression multiply of type (Int, Int) -> Int, which takes two integers as input parameters (x and y) and returns their product (x * y). We then assign the lambda expression to a variable multiply.

Inside the "main()" function, we define two numbers num1 and num2. We then invoke the multiply lambda expression by passing num1 and num2 as arguments and store the result in the result variable. The println() function is used to print the result.

Kotlin Editor:


Previous: Kotlin Recursion Function Exercises Home.
Next: Lambda expression for finding the square of a number.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.