自定义For循环

实现类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
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,660评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 10,765评论 0 23
  • #20170509自由读第一次打卡# 《你的生命有什么可能》p68-80 关于价值观:做个有定见的人 当要得到更多...
    雪23阅读 113评论 0 0
  • 时间还早,夜还长。哪怕天上云雾浓重,你也知道圆满的月亮就在某一片云背后,兀自发亮。人生就是这样,说稀奇不稀奇,说平...
    Holidayq阅读 293评论 0 0
  • 我投世界以温柔,愿世界也能报我以温柔! ――醉朝歌
    醉朝歌阅读 225评论 0 0

友情链接更多精彩内容