Kotlin KoansでKotlin入門 第16回:For loop
8153 ワード
はじめに
公式の問題集「Kotlin Koans」を解きながらKotlinを学習します。
過去記事はこちら
- Introduction
- Classes
- Conventions
問題
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)
}
}
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)
}
}
Author And Source
この問題について(Kotlin KoansでKotlin入門 第16回:For loop), 我々は、より多くの情報をここで見つけました https://qiita.com/kosuke1/items/f5f6eeea41fb89b2a20c著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .