w3resource

Kotlin Program: Lambda expression for multiplying two numbers

Kotlin Lambda: Exercise-1 with Solution

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

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.