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:
- 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 objectsDate(year:Int,month:Int,day:Int)
. Second, we continue to work on twoProduct(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 <,>,==
.
More at:
https://grokonez.com/kotlin/kotlin-compare-objects-comparable-example
Kotlin – Compare Objects with Comparable Example
Top comments (0)