Iterator 3个月前

编程语言
773
Iterator

Iterable

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

Iterator

  • next()
  • hasNext()
public interface Iterator<out T> {
    /**
     * Returns the next element in the iteration.
     */
    public operator fun next(): T

    /**
     * Returns `true` if the iteration has more elements.
     */
    public operator fun hasNext(): Boolean
}
/**
 * Given an [iterator] function constructs an [Iterable] instance that returns values through the [Iterator]
 * provided by that function.
 */
@kotlin.internal.InlineOnly
public inline fun <T> Iterable(crossinline iterator: () -> Iterator<T>): Iterable<T> = object : Iterable<T> {
    override fun iterator(): Iterator<T> = iterator()
}
fun main(args: Array<String>) {

    var x = 5
    while(x > 0){
        println(x)
        x--
    }

    do{
        println(x)
        x--
    }while (x > 0)

//    for (arg in args){
//        println(arg)
//    }
//
//    for((index, value) in args.withIndex()){
//        println("$index -> $value")
//    }
//
//    for(indexedValue in args.withIndex()){
//        println("${indexedValue.index} -> ${indexedValue.value}")
//    }
//
//    val list = MyIntList()
//    list.add(1)
//    list.add(2)
//    list.add(3)
//
//    for(i in list){
//        println(i)
//    }
}

class MyIterator(val iterator: Iterator<Int>){
    operator fun next(): Int{
        return iterator.next()
    }

    operator fun hasNext(): Boolean{
        return iterator.hasNext()
    }
}

class MyIntList{
    private val list = ArrayList<Int>()

    fun add(int : Int){
        list.add(int)
    }

    fun remove(int: Int){
        list.remove(int)
    }

    operator fun iterator(): MyIterator{
        return MyIterator(list.iterator())
    }
}
image
EchoEcho官方
无论前方如何,请不要后悔与我相遇。
1377
发布数
439
关注者
2223812
累计阅读

热门教程文档

Dart
35小节
Spring Cloud
8小节
QT
33小节
C#
57小节
Swift
54小节