Iterable

  1. public interface Iterable<out T> {
  2. /**
  3. * Returns an iterator over the elements of this object.
  4. */
  5. public operator fun iterator(): Iterator<T>
  6. }

Iterator

  • next()
  • hasNext()
  1. public interface Iterator<out T> {
  2. /**
  3. * Returns the next element in the iteration.
  4. */
  5. public operator fun next(): T
  6. /**
  7. * Returns `true` if the iteration has more elements.
  8. */
  9. public operator fun hasNext(): Boolean
  10. }
  1. /**
  2. * Given an [iterator] function constructs an [Iterable] instance that returns values through the [Iterator]
  3. * provided by that function.
  4. */
  5. @kotlin.internal.InlineOnly
  6. public inline fun <T> Iterable(crossinline iterator: () -> Iterator<T>): Iterable<T> = object : Iterable<T> {
  7. override fun iterator(): Iterator<T> = iterator()
  8. }
  1. fun main(args: Array<String>) {
  2. var x = 5
  3. while(x > 0){
  4. println(x)
  5. x--
  6. }
  7. do{
  8. println(x)
  9. x--
  10. }while (x > 0)
  11. // for (arg in args){
  12. // println(arg)
  13. // }
  14. //
  15. // for((index, value) in args.withIndex()){
  16. // println("$index -> $value")
  17. // }
  18. //
  19. // for(indexedValue in args.withIndex()){
  20. // println("${indexedValue.index} -> ${indexedValue.value}")
  21. // }
  22. //
  23. // val list = MyIntList()
  24. // list.add(1)
  25. // list.add(2)
  26. // list.add(3)
  27. //
  28. // for(i in list){
  29. // println(i)
  30. // }
  31. }
  32. class MyIterator(val iterator: Iterator<Int>){
  33. operator fun next(): Int{
  34. return iterator.next()
  35. }
  36. operator fun hasNext(): Boolean{
  37. return iterator.hasNext()
  38. }
  39. }
  40. class MyIntList{
  41. private val list = ArrayList<Int>()
  42. fun add(int : Int){
  43. list.add(int)
  44. }
  45. fun remove(int: Int){
  46. list.remove(int)
  47. }
  48. operator fun iterator(): MyIterator{
  49. return MyIterator(list.iterator())
  50. }
  51. }