data class CustomDate( val year: Int, val month: Int, val day: Int ) : Comparable<CustomDate> { override fun compareTo(other: CustomDate): Int { if (year == other.year) { if (month == other.month) { return day - other.day } else { return month - other.month } } else { return year - other.year } } override fun toString(): String { return "year: $year, month: $month, day: $day" } } fun main() { var custumDates = listOf( CustomDate(2023, 1, 1), CustomDate(2023, 1, 2), CustomDate(2023, 2, 1), CustomDate(2022, 1, 1), CustomDate(2022, 1, 2), CustomDate(2022, 2, 1) ) .shuffled() .sorted() for (customDate in custumDates) { println(customDate.toString()) } }
出力は:
year: 2022, month: 1, day: 1
year: 2022, month: 1, day: 2
year: 2022, month: 2, day: 1
year: 2023, month: 1, day: 1
year: 2023, month: 1, day: 2
year: 2023, month: 2, day: 1