Kotlin KoansでKotlin入門 第14回:Comparison


はじめに

公式の問題集「Kotlin Koans」を解きながらKotlinを学習します。

過去記事はこちら

問題

Comparison

演算子のオーバーロードについて、また、==、<、+といった演算の異なる規則がKotlinでどのように機能するかについて学びます。
クラスMyDateに関数compareToを追加して、比較できるようにします。
この後、以下の date1 < date2 のコードがコンパイルされ始めるはずです。
Kotlinでメンバをオーバーライドする場合、override修飾子が必須であることに注意してください。

修正前のコード

data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) : Comparable<MyDate> {
    /* TODO */
}

fun test(date1: MyDate, date2: MyDate) {
    // this code should compile:
    println(date1 < date2)
}

問題のポイント

Kotlinでは、型に対してあらかじめ定義された演算子のセットに対して、カスタム実装を提供することができます。これらの演算子は、あらかじめ定義された記号表現(+や*など)と優先順位を持ちます。

例として、単項のマイナス演算子をオーバーロードする方法を紹介します。

data class Point(val x: Int, val y: Int)

operator fun Point.unaryMinus() = Point(-x, -y)

val point = Point(10, 20)

fun main() {
   println(-point)  // prints "Point(x=-10, y=-20)"
}

解答例

すべての比較はcompareToの呼び出しに変換され、Intを返すようにします。

data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) : Comparable<MyDate> {
    override fun compareTo(other: MyDate) = when {
        year != other.year -> year - other.year
        month != other.month -> month - other.month
        else -> dayOfMonth - other.dayOfMonth
    }
}

fun test(date1: MyDate, date2: MyDate) {
    // this code should compile:
    println(date1 < date2)
}