Back to Blog

Kotin: Create an extension function for Integer to check if it is prime or not

Sandy LaneSandy Lane

Video: Kotin: Create an extension function for Integer to check if it is prime or not by Taught by Celeste AI - AI Coding Coach

Watch full page →

Kotlin: Create an Extension Function for Integer to Check if It Is Prime

In Kotlin, extension functions allow you to add new functionality to existing classes without modifying their source code. This example demonstrates how to create an extension function for the Integer type to determine whether a number is prime, enhancing readability and reusability in your code.

Code

fun Int.isPrime(): Boolean {
  if (this <= 1) return false  // Numbers less than or equal to 1 are not prime
  if (this == 2) return true    // 2 is the only even prime number
  if (this % 2 == 0) return false  // Exclude other even numbers

  val sqrt = kotlin.math.sqrt(this.toDouble()).toInt()
  for (i in 3..sqrt step 2) {
    if (this % i == 0) return false  // Divisible by a number other than 1 and itself
  }
  return true  // No divisors found, number is prime
}

// Example usage:
fun main() {
  val number = 29
  println("$number is prime? ${number.isPrime()}")
}

Key Points

  • Extension functions let you add methods to existing types like Int without inheritance.
  • The isPrime() function efficiently checks primality by testing divisibility up to the square root.
  • Handling special cases like numbers less than 2 and even numbers improves performance.
  • Using step 2 in the loop skips even numbers, reducing unnecessary checks.
  • Calling the extension function on any Int instance makes prime checks concise and expressive.