美文网首页
自定义For循环

自定义For循环

作者: Azur_wxj | 来源:发表于2018-02-19 21:26 被阅读14次

    实现类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
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:自定义For循环

          本文链接:https://www.haomeiwen.com/subject/sqdwtftx.html