Kotlin – Compare Objects with Comparable Example
Kotlin
87
compare
1
comparable
3
Male avatar

loveprogramming viết ngày 16/04/2021

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:

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 <,>,==.

More at:

https://grokonez.com/kotlin/kotlin-compare-objects-comparable-example

Kotlin – Compare Objects with Comparable Example

Bình luận


White
{{ comment.user.name }}
Bỏ hay Hay
{{comment.like_count}}
Male avatar
{{ comment_error }}
Hủy
   

Hiển thị thử

Chỉnh sửa

Male avatar

loveprogramming

447 bài viết.
78 người follow
Kipalog
{{userFollowed ? 'Following' : 'Follow'}}
Cùng một tác giả
Male avatar
1 0
Tutorial Link: (Link) (Ảnh) Django is a Pythonbased free and opensource web framework that follows the modeltemplateview architectural pattern. A...
loveprogramming viết 6 tháng trước
1 0
Male avatar
1 0
https://loizenai.com/angular11nodejspostgresqlcrudexample/ Angular 11 Node.js PostgreSQL Crud Example (Ảnh) Tutorial: “Angular 11 Node.js Postg...
loveprogramming viết 5 tháng trước
1 0
Male avatar
1 0
Angular Spring Boot jwt Authentication Example Github https://loizenai.com/angularspringbootjwt/ (Ảnh) Tutorial: ” Angular Spring Boot jwt Authe...
loveprogramming viết 5 tháng trước
1 0
Bài viết liên quan
Male avatar
0 0
https://grokonez.com/kotlin/kotlinreadwritecsvfileexample How to read/write CSV file in Kotlin In this tutorial, we're gonna look at examples tha...
loveprogramming viết 7 ngày trước
0 0
{{like_count}}

kipalog

{{ comment_count }}

bình luận

{{liked ? "Đã kipalog" : "Kipalog"}}


Male avatar
{{userFollowed ? 'Following' : 'Follow'}}
447 bài viết.
78 người follow

 Đầu mục bài viết

Vẫn còn nữa! x

Kipalog vẫn còn rất nhiều bài viết hay và chủ đề thú vị chờ bạn khám phá!