Iterable Iterator

简单场景描述 我们拥有一个数据类MyDate ,一个获取下一天的方法followingDate以及重写rangeTo操作符。 data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) : Comparable<MyDate> { override fun compareTo(other: MyDate): Int = when { year != other.year -> year - other.year month != other.month -> month - other.month else -> dayOfMonth - other.dayOfMonth } fun followingDate(): MyDate { val localDate = LocalDate.of(year, month, dayOfMonth) val nextDay = localDate.plusDays(1) return MyDate(nextDay.year, nextDay.monthValue, nextDay.dayOfMonth) } operator fun rangeTo(other: MyDate): DateRange = DateRange(this, other) } 我们想要使用for loop来遍历MyDate区间中的每一天。 fun iterateOverDateRange(firstDate: MyDate, secondDate: MyDate, handler: (MyDate) -> Unit) { for (date in firstDate..secondDate) { handler(date) } } 那么我们的目标是:Make the class DateRange implement Iterable<MyDate> ,正确答案如下。 ...

July 5, 2025 · 2 min