自定义For循环

2018-02-19  本文已影响14人  Azur_wxj

实现类Iterator的两个抽象方法:

abstract def hasNext: Boolean

Tests whether this iterator can provide another element.

abstract def next(): A

Produces the next element of this iterator.

例如:

import scala.language.implicitConversions
object RangeLike{
    implicit def int2RangeLike(num:Int)=new RangeLike(num)
}
class RangeLike(private val start:Int) extends Iterator[Int]{
    var counter=start-1
    private var end:Int=0
    def |-> (end:Int)={
        this.end=end;
        this
    }
    def hasNext={counter<end}
    def next()={
        counter+=1
        counter
    }
}

object Main{
    import RangeLike._
    def main(args:Array[String])={
        for(i <- 1|->9){
            print(i)  //123456789
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读