compareValuesByを使ってもっと簡単にComparableを実装する

data class CustomDate(
    val year: Int,
    val month: Int,
    val day: Int
) : Comparable<CustomDate> {
    override fun compareTo(other: CustomDate): Int {
        return compareValuesBy(this, other, CustomDate::year, CustomDate::month, CustomDate::day)
    }

    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