Comparable interface in Kotlin

Since Kotlin provides the programmer, to define new types in terms of classes, there must be a way to compare the instances of these classes. As in Java, the Comparable interface provides a compareTo() function to compare two objects. Kotlin provides this through the Comparable interface. However, it also provides certain extension functions, which provides much more functionality. Kotlin also provides an additional advantage that the instance implementing Comparable interface can be compared using relational operators.

Functions –

compareTo() –
This function compares the calling object with the passed object. It returns zero, if both are equal, a negative number if the passed object is greater, otherwise it returns a positive number.

abstract operator fun compareTo(other: T): Int

Extension Functions –

coerceAtLeast() –
This function checks whether the calling object is greater than a certain minimum object. It returns current object if it is greater otherwise returns the minimum object

fun <T : Comparable> T.coerceAtLeast(minimumValue: T): T

coerceAtMost() –
This function checks whether the calling object is smaller than the given maximum object. It returns the current object if its smaller, otherwise returns the maximum object.

fun <T : Comparable> T.coerceAtMost(maximumValue: T): T

coerceIn() –
This function checks whether the calling object is within a certain minimum and maximum value. It returns the object if it is in the range, otherwise returns minimum if object is less than the minimum, else returns the maximum.

fun <T : Comparable> T.coerceIn(
    minimumValue: T?, 
    maximumValue: T?
): T

Example to demonstrate the Comparable interface –

filter_none

edit
close

play_arrow

link
brightness_4
code

class Rectangle(val length: Int, val breadth: Int): Comparable<Rectangle>{
    override fun compareTo(other: Rectangle): Int {
        val area1 = length * breadth
        val area2 = other.length * other.breadth
  
        // Comparing two rectangles on the basis of area
        if(area1 == area2){
            return 0;
        }else if(area1 < area2){
            return -1;
        }
        return 1;
    }
}
  
fun main(){
    var obj1 = Rectangle(5,5)
    var obj2 = Rectangle(4,4)
    var min = Rectangle(2,2)
    var max = Rectangle(9,9)
  
    // Using relational operator compare two rectangles
    println("Is rectangle one greater than equal"+
                " to rectangle two? ${obj1>obj2}")
    println("Is rectangle one greater than the " +
            "minimum sized rectangle? ${obj1.coerceAtLeast(min) == obj1} ")
  
    obj2 = Rectangle(10,10)
    println("Is rectangle two smaller than " +
            "the maximum sized rectangle? ${obj2.coerceAtMost(max) == obj2}")
  
    println("Is rectangle one within " +
            "the bounds? ${obj1.coerceIn(min,max) == obj1}")
}

chevron_right


Output:

Is rectangle one greater than equal to rectangle two? true
Is rectangle one greater than the minimum sized rectangle? true 
Is rectangle two smaller than the maximum sized rectangle? false
Is rectangle one within the bounds? true

rangeTo() –
This function checks whether the value lie within the range or not. If value not found in range then return false, else return true. Here numbers are compared according to IEEE-754 standard.

operator fun > T.rangeTo(
    that: T
): ClosedRange

Kotlin program to use the rangeTo() function –

filter_none

edit
close

play_arrow

link
brightness_4
code

fun main(args : Array<String>) {
    val range = 1..1000
    println(range)
  
    println("Is 55 within the range? ${55 in range}") // true
    println("Is 100000 within the range? ${100000 in range}") // false
}

chevron_right


Output:

1..1000
Is 55 within the range? true
Is 100000 within the range? false


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.