LoginSignup
0
0

More than 1 year has passed since last update.

Kotlin KoansでKotlin入門 第16回:For loop

Posted at

はじめに

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

過去記事はこちら

問題

For loop

DateRangeクラスにIterable<MyDate>を実装して、反復処理できるようにします。DateUtil.kt で定義されている MyDate.followingDate() 関数を使用します。
次の日付を見つけるロジックを独自に実装する必要はありません。
オブジェクト式は、KotlinではJavaの無名クラスと同じような役割を担っています。


修正前のコード

class DateRange(val start: MyDate, val end: MyDate)

fun iterateOverDateRange(firstDate: MyDate, secondDate: MyDate, handler: (MyDate) -> Unit) {
    for (date in firstDate..secondDate) {
        handler(date)
    }
}

問題のポイント

Kotlinのforループは、対応するイテレータメンバーや拡張関数があれば、どんなオブジェクトでも反復処理することができます。

解答例

class DateRange(val start: MyDate, val end: MyDate):Iterable<MyDate> {
    override fun iterator(): Iterator<MyDate> {
        return object : Iterator<MyDate> {
            var current: MyDate = start

            override fun next(): MyDate {
                if (!hasNext()) throw NoSuchElementException()
                val result = current
                current = current.followingDate()
                return result
            }

            override fun hasNext(): Boolean = current <= end
        }
    }
}
    

fun iterateOverDateRange(firstDate: MyDate, secondDate: MyDate, handler: (MyDate) -> Unit) {
    for (date in firstDate..secondDate) {
        handler(date)
    }
}
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