This tutorial shows you way to compare Objects with Comparable
by an example.
>>> Refer to: JavaSampleApproach.com
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
1 2 3 4 5 6 7 8 9 10 11 12 13 |
package com.kotlination.objcomparision import kotlin.Comparable data class Date(val year: Int, val month: Int, val day: Int) : Comparable<Date> { 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 <,>,==
.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
package com.kotlination.objcomparision import kotlin.Comparable data class Product(val name: String, val releasedDate: Date) : Comparable<Product> { override fun compareTo(other: Product) = when { releasedDate < other.releasedDate -> -1 releasedDate > other.releasedDate -> 1 else -> 0 } } |
2. Create test function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
package com.kotlination.objcomparision fun main(args: Array<String>) { 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
1 2 3 4 |
=== 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 |