Comparable interface in Kotlin

14 Jul, 2019
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.
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

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 –
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}")}
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 –
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}
Output:
1..1000
Is 55 within the range? true
Is 100000 within the range? false

Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android RecyclerView in Kotlin
Broadcast Receiver in Android With Example
How to Communicate Between Fragments in Android?
Content Providers in Android with Example
Retrofit with Kotlin Coroutine in Android
Kotlin constructor
Kotlin Setters and Getters
How to Add and Customize Back Button of Action Bar in Android?
Kotlin Higher-Order Functions