1. Overview

In this tutorial, we’ll see a simple solution for a classic programming challenge: deciding if a number is even (divisible by 2) or odd (non-divisible by 2). We’ll see how the rem() operator works in Kotlin, and see samples of how we can use it to check a number’s divisibility by 2.

2. The rem Operator

As in many programming languages, Kotlin provides the remainder/modulo operator, represented by the symbol ‘*%*‘ or the rem() function. The rem() operation gives you the remainder of the division of two numbers. For example, 5 % 2 returns 1, as 2 fits twice in 5 and 1 remains from the operation. This is modulo division.

Because of operator overloading, Kotlin translates x % y to x.rem(y). To understand better how operator overloading works, read our article Operator Overloading in Kotlin. Kotlin used to call this operator “mod“, short for modulo. This was changed to rem() in version 1.1 (see patch notes).

2.1. The Modulo Operation

Let’s take a look at some examples of what we expect from the modulo operation:

@Test
fun `Given the remainder function, assertions on the remainder should pass`() {
  assertTrue(10 % 4 == 2)
  assertTrue(25 % 5 == 0)
  assertTrue(24 % 5 == 4)
  assertTrue(100 % 20 == 0)
}

2.2. Checking for Even or Odd

Let’s prepare a couple of variables to be our subjects under test:

val a = 42
val b = 25

To check if a number is even or odd, we take the remainder of the division by 2 and verify:

  • Is the remainder 0? Then the number must be even.
  • Is the remainder 1? Then the number must be odd.

Let’s apply this concept to our variables:

@Test
fun `Given odd or even numbers should get the right response from rem`() {
  val a = 42
  val b = 25

  val aRem2 = a % 2
  val bRem2 = b % 2
  val isAEven: Boolean = aRem2 == 0
  val isBEven: Boolean = bRem2 == 0

  assertTrue(isAEven)
  assertFalse(isBEven)
}

Expanding on what we’ve just learned, let’s continue with two functions, isOdd() and isEven():

fun isEven(value: Int) = value % 2 == 0
fun isOdd(value: Int) = value % 2 == 1

Let’s write some unit tests to validate our functions:

@Test
fun `Given odd and even values the isEven function should answer correctly`() {
  assertTrue(isEven(2))
  assertTrue(isEven(4))
  assertTrue(isEven(6))

  assertFalse(isEven(1))
  assertFalse(isEven(3))
}

@Test
fun `Given odd and even values the isOdd function should answer correctly`() {
  assertTrue(isOdd(1))
  assertTrue(isOdd(3))
  assertTrue(isOdd(5))

  assertFalse(isOdd(2))
  assertFalse(isOdd(4))
}

3. Conclusion

We’ve learned about the rem() function and % operator and how they’re used in Kotlin. We applied the operator to a couple of variables to understand how we can use it in our code and generalized this concept into utility functions.

The code and examples in the article can be found over on GitHub.