DEV Community

loizenai
loizenai

Posted on

Kotlin – Compare Objects with Comparable Example

https://grokonez.com/kotlin/kotlin-compare-objects-comparable-example

Kotlin – Compare Objects with Comparable Example

This tutorial shows you way to compare Objects with Comparable by an example.

Related posts:

I. Technology

  • Java 1.8
  • Kotlin 1.1.2

    II. Overview

    1. Goal

    First, we compare two objects Date(year:Int,month:Int,day:Int). Second, we continue to work on two Product(name:String,date:Date) objects.

    2. Steps to do

  • Implement Comparable interface for the class of objects you want to compare.
  • Override compareTo(other: T) method and:
  • return zero if this object is equal other
  • a negative number if it's less than other
  • a positive number if it's greater than other

    III. Practice

    1. Create Classes

    
    package com.javasampleapproach.objcomparision

import kotlin.Comparable

data class Date(val year: Int, val month: Int, val day: Int) : Comparable {

override fun compareTo(other: Date) = when {
    year != other.year -> year - other.year
    month != other.month -> month - other.month
    else -> day - other.day
}
Enter fullscreen mode Exit fullscreen mode

}

Product class includes Date field (implemented Comparable interface), so you can compare two Date objects inside using operator <,>,==.

More at:

https://grokonez.com/kotlin/kotlin-compare-objects-comparable-example

Kotlin – Compare Objects with Comparable Example

Top comments (0)