Kotlin Program: Lambda expression to check if a number is even
Write a Kotlin program that implements a lambda expression to check if a number is even.
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 and anonymous function in Kotlin. It allows defining small functions in a compact way.
- Function Types: Kotlin allows defining function types such as (Int) -> Boolean, meaning a function that takes an integer and returns a boolean.
- Modulus Operator (%): The modulus operator returns the remainder of a division. It can be used to check if a number is even (a number is even if num % 2 == 0).
- Function Invocation: Once a lambda is stored in a variable, it can be invoked like a regular 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: Create a lambda expression that takes an integer as input and returns a boolean.
- Hint 2: Use the modulus operator (%) to check if the number is even.
- Hint 3: Assign the lambda expression to a variable with a function type of (Int) -> Boolean.
- Hint 4: Call the lambda by passing a number as an argument and print the result using println().
Sample Solution:
Kotlin Code:
fun main() {
val isEven: (Int) -> Boolean = { num -> num % 2 == 0 }
val number = 8
//val number = 7
val result = isEven(number)
println("$number is even: $result")
}
Sample Output:
8 is even: true 7 is even: false
Explanation:
In the above exercise -
First we declare a lambda expression isEven of type (Int) -> Boolean, which takes an integer num as an input parameter and checks if it is even by using the condition num % 2 == 0. If the number is even, the lambda expression returns true, otherwise it returns false.
Inside the "main()" function, we define a number "number". We then invoke the isEven lambda expression by passing "number" as an argument and store the result in the result variable. The result is then printed using println.
Kotlin Editor:
Previous: Lambda expression for finding the square of a number.
Next: Lambda expression for calculating the average of numbers.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics