-
Notifications
You must be signed in to change notification settings - Fork 109
/
Iterator.kt
38 lines (30 loc) · 817 Bytes
/
Iterator.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package design_patterns
/**
*
* Iterator is a behavioral design pattern that provides a mechanism for sequentially enumerating the elements
*
* of a collection without revealing its internal representation.
*
*/
interface BoxIterator<T> {
fun hasNext(): Boolean
fun next(): T
}
interface BoxIterable<T> {
fun iterator(): BoxIterator<T>
}
class GiftBox(private val presents: Array<String>) : BoxIterable<String> {
override fun iterator() = object : BoxIterator<String> {
private var current = -1
override fun next(): String {
return presents[current]
}
override fun hasNext(): Boolean {
if (current < presents.size - 1) {
current++
return true
}
return false
}
}
}