w3resource

Kotlin infix Function: Check if the number is divisible

Kotlin Function: Exercise-19 with Solution

Write an Kotlin infix function that checks if a number is divisible by another number.

Sample Solution:

Kotlin Code:

infix fun Int.isDivisibleBy(divisor: Int): Boolean {
    return this % divisor == 0
}

fun main() {
    val number1 = 15
    val number2 = 3

    println("$number1 is divisible by $number2: ${number1.isDivisibleBy(number2)}")
    println("$number2 is divisible by $number1: ${number2.isDivisibleBy(number1)}")
}

Sample Output:

15 is divisible by 3: true
3 is divisible by 15: false

Explanation:

In the above exercise -

  • First we define an infix function called "isDivisibleBy()" using the infix keyword. The function is defined as an extension function of the Int class, which means it can be called directly on an integer value. It takes another integer value called a divisor as an argument.
  • Inside the function, we check if the current integer value (this) is divisible by the divisor using the modulo operator %. If the remainder is 0, it means the number is divisible, so the function returns true. Otherwise, it returns false.
  • In the "main()" function, we demonstrate the infix function by checking the divisibility of number1 by number2 and vice versa. We print the results using println along with the corresponding numbers.

Kotlin Editor:


Previous: Calculate the average of variable number of arguments.
Next: Calculate 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.