w3resource

Kotlin Program: Lambda expression for finding the square of a number


Write a Kotlin program that implements a lambda expression to find the square of a number 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 concise way to define an anonymous function. In Kotlin, lambda expressions are enclosed within curly braces { } and can take parameters and return values.
  • Function Types: Kotlin allows defining function types explicitly. For example, (Int) -> Int represents a function that takes an integer and returns an integer.
  • Using Lambda Expressions: Lambdas can be stored in variables and invoked like regular functions.
  • Function Invocation: Once a lambda is assigned to a variable, you can call it 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 an integer as a parameter and returns its square.
  • Hint 2: Assign the lambda expression to a variable with a function type of (Int) -> Int.
  • Hint 3: Call the lambda expression by passing an integer value and store the result in a variable.
  • Hint 4: Use println() to display the squared result.

Sample Solution:

Kotlin Code:

fun main() {
    val square: (Int) -> Int = { num -> num * num }

    val number = 7

    val result = square(number)
    println("The square of $number is: $result")
}

Sample Output:

The square of 7 is: 49

Explanation:

In the above exercise -

At first we declare a lambda expression square of type (Int) -> Int, which takes an integer num as an input parameter and returns its square (num * num). We assign the lambda expression to a variable square.

Inside the "main()" function, we define a number "number". We then invoke the square lambda expression by passing "number" as an argument and store the result in the result variable. Finally, we print the result.

Go to:


PREV : Lambda expression for multiplying two numbers.
NEXT : Lambda expression to check if a number is even.

Kotlin Editor:


Improve this sample solution and post your code through Disqus

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.