Kotlin compareTo()

Kotlin compareTo()

The compareTo() function in Kotlin is used for comparing the values of two objects. It returns a negative integer, zero, or a positive integer based on whether the current object is less than, equal to, or greater than the specified object respectively.

Syntax

The syntax of the compareTo() function is:

fun compareTo(other: T): Int

where

ParameterDescription
otherThe object to be compared with.
Parameter of compareTo() function

The compareTo() function returns a negative integer, zero, or a positive integer, depending on the comparison result:

  • Negative integer: Current object is less than the other object.
  • Zero: Current object is equal to the other object.
  • Positive integer: Current object is greater than the other object.

Examples

1. Comparing Integers using compareTo() function

In this example, we’ll use compareTo() to compare two integer values.

Kotlin Program

fun main() {
    val num1 = 10
    val num2 = 5

    val result = num1.compareTo(num2)

    when {
        result < 0 -> println("$num1 is less than $num2")
        result == 0 -> println("$num1 is equal to $num2")
        result > 0 -> println("$num1 is greater than $num2")
    }
}

Output

10 is greater than 5

In this example, the compareTo() function is used to compare two integer values, and the result is printed based on the comparison.

2. Comparing Strings using compareTo() function

We can also use compareTo() to compare strings lexicographically.

Kotlin Program

fun main() {
    val str1 = "apple"
    val str2 = "banana"

    val result = str1.compareTo(str2)

    when {
        result < 0 -> println("$str1 comes before $str2")
        result == 0 -> println("$str1 is equal to $str2")
        result > 0 -> println("$str1 comes after $str2")
    }
}

Output

apple comes before banana

In this example, the compareTo() function is used to compare two strings lexicographically.

Summary

In this tutorial, we’ve covered the Kotlin compareTo() function, its syntax, and how to use it for comparing objects. The function is particularly useful for sorting and ordering elements in a collection.