LoginSignup
0
0

More than 1 year has passed since last update.

Kotlin KoansでKotlin入門 第17回:Operators overloading

Posted at

はじめに

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

過去記事はこちら

問題

Operators overloading

日付に年、週、日を加えることをサポートする日付演算を実装してください。date + YEAR * 2 + WEEK * 3 + DAY * 15のようなコードを書くことができます。
まず、MyDateにTimeIntervalを引数として、拡張関数plus()を追加します。DateUtil.kt で宣言されているユーティリティ関数 MyDate.addTimeIntervals() を使用します。
そして、1つの日付にいくつかの時間間隔を加えることに対応してみてください。追加クラスが必要かもしれません。

修正前のコード

import TimeInterval.*

data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int)

// Supported intervals that might be added to dates:
enum class TimeInterval { DAY, WEEK, YEAR }

operator fun MyDate.plus(timeInterval: TimeInterval): MyDate = TODO()

fun task1(today: MyDate): MyDate {
    return today + YEAR + WEEK
}

// fun task2(today: MyDate): MyDate {
//     TODO("Uncomment") //return today + YEAR * 2 + WEEK * 3 + DAY * 5
// }

問題のポイント

算術演算子+*をオーバーライドします。

解答例

import TimeInterval.*

data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int)

// Supported intervals that might be added to dates:
enum class TimeInterval { DAY, WEEK, YEAR }

operator fun MyDate.plus(timeInterval: TimeInterval): MyDate = addTimeIntervals(timeInterval, 1)

class RepeatedTimeInterval(val timeInterval: TimeInterval, val number: Int)

operator fun TimeInterval.times(number: Int) = RepeatedTimeInterval(this, number)

operator fun MyDate.plus(timeIntervals: RepeatedTimeInterval) =
    addTimeIntervals(timeIntervals.timeInterval, timeIntervals.number)

fun task1(today: MyDate): MyDate {
    return today + YEAR + WEEK
}

fun task2(today: MyDate): MyDate {
    return today + YEAR * 2 + WEEK * 3 + DAY * 5
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0