Description
Read about operator overloading to learn how different conventions for operations like
==,<,+work in Kotlin. Add the functioncompareToto the class MyDate to make it comparable. After that the code belowdate1 < date2will start to compile.In Kotlin when you override a member, the modifier
overrideis mandatory.
演算子のオーバーロード を読み、
==、<、+などの演算がKotlinでどのように機能するかを確認してください。 MyDateクラスにcompareTo関数を追加し、MyDateクラスの比較ができるように実装してください。 以下のコードdate1 < date2がコンパイルできるようになります。Kotlinで演算子をオーバーライドする際は、
override修飾子が必須となります。
Code
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 compare(date1: MyDate, date2: MyDate) = date1 < date2
Memo
- Kotlinでは
+や*といった演算子をオーバーロードできる- 独自クラスでも、演算子を使えるようになる
- オーバーロードできる演算子