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

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

2. Create test function

3. Run & check Result

By grokonez | August 28, 2017.

Last updated on February 7, 2020.

Related Posts

Got Something To Say:

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