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:
Date(year:Int,month:Int,day:Int)
.
Second, we continue to work on two Product(name:String,date:Date)
objects.
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
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
#kotlin #comparable