Last active
June 1, 2023 00:34
-
-
Save enshahar/a803927341480686bfdcf18073cefbee to your computer and use it in GitHub Desktop.
Iterable, Iterator, operator iterator(), operator hasNext(), operator next()와 for 루프
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyIterable(private val n:Int): Iterable<Int> { | |
override fun iterator(): Iterator<Int> = MyIterator(n) | |
} | |
class MyIterator(private val max: Int): Iterator<Int> { | |
private var n:Int=0 | |
override fun next():Int = n | |
override fun hasNext(): Boolean = n++ < max | |
} | |
class IterableLike(private val n:Int) { | |
operator fun iterator(): IteratorLike = IteratorLike(n) | |
} | |
class IteratorLike(private val max: Int) { | |
private var n:Int=0 | |
operator fun next():Int = n | |
operator fun hasNext(): Boolean = n++ < max | |
} | |
fun main() { | |
val iterable = MyIterable(10) | |
val iterator = MyIterator(10) | |
val iterableLike = IterableLike(10) | |
val iteratorLike = IteratorLike(10) | |
var sum = 0 | |
for(i in iterable) sum += i | |
println(sum) | |
sum = 0 | |
for(i in iterator) sum += i | |
println(sum) | |
sum = 0 | |
for(i in iterableLike) sum += i | |
println(sum) | |
sum = 0 | |
for(i in iteratorLike) sum += i // For-loop range must have an 'iterator()' method | |
println(sum) | |
} | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment