w3resource

Kotlin infix Function: Check if the number is divisible


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


Pre-Knowledge (Before you start!)

  • Basic Kotlin Syntax: Familiarity with writing and running Kotlin programs.
  • Kotlin Functions: Understanding how to define and call functions in Kotlin.
  • Infix Functions: Knowledge of using the infix keyword to create custom infix functions.
  • Extension Functions: Awareness of how to extend existing classes, such as Int, with new functionality.
  • Modulo Operator: Understanding the modulo operator (%) to check divisibility between numbers.
  • Printing Output: Familiarity with the println() function to display output on the screen.

Hints (Try before looking at the solution!)

  • Define the Infix Function.
  • Check Divisibility.
  • Call the Function.
  • Use Infix Notation.
  • Display the Output.
  • Test with Different Numbers.
  • Common Errors to Avoid:
    • Forgetting the infix keyword.
    • Misplacing modulo logic.
    • Not handling divisor = 0.

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.