Kotlin – Compare Objects with Comparable Example

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

Related posts:
Kotlin – Sort List of Objects with Comparable
Kotlin – Sort List of Objects with Kotlin Comparator Example
Kotlin Comparator Binary Search for Object List

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
	}
	
}

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


package com.javasampleapproach.objcomparision

import kotlin.Comparable

data class Product(val name: String, val releasedDate: Date) : Comparable {

	override fun compareTo(other: Product) = when {
		releasedDate < other.releasedDate -> -1
		releasedDate > other.releasedDate -> 1
		else -> 0
	}

}

2. Create test function


package com.javasampleapproach.objcomparision

fun main(args: Array) {

	println("=== Check Date Comparision ===")
	val date1 = Date(2007, 6, 29)
	val date2 = Date(2010, 4, 3)

	val compResult1 = when {
		date1 < date2 -> "BEFORE"
		date1 > date2 -> "AFTER"
		else -> "WITH"
	}

	println(date1.toString() + " -- comes " + compResult1 + " -- " + date2.toString())

	println("=== Check Product Comparision ===")
	val product1 = Product("Tablet", Date(2010, 4, 3))
	val product2 = Product("Smartphone", Date(2007, 6, 29))

	val compResult2 = when {
		product1 < product2 -> "BEFORE"
		product1 > product2 -> "AFTER"
		else -> "WITH"
	}

	println(product1.name + " -- comes " + compResult2 + " -- " + product2.name)
}

3. Run & check Result


=== Check Date Comparision ===
Date(year=2007, month=6, day=29) -- comes BEFORE -- Date(year=2010, month=4, day=3)
=== Check Product Comparision ===
Tablet -- comes AFTER -- Smartphone


By grokonez | August 28, 2017.

Last updated on April 16, 2021.



Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*