Iterating circular way

后端 未结 4 1383
甜味超标
甜味超标 2021-01-11 11:14

I need iterate through a List but circular way. I need too add new elements to the list and iterate over all elements (olds and news elements), How I do it? Is there any dat

4条回答
  •  渐次进展
    2021-01-11 11:47

    This sort of thing really deserves to be in standard stream library, but doesn't appear to be. dbryne's answer with a stream works well, or if you prefer it in for-comprehension form

    val listToRepeat:List[Foo]
    val forever:Stream[Foo] = for(x<-Stream.continually(1); y<-listToRepeat) yield y
    

    The first stream generator keeps things going forever even though you are ignoring the value. The second generator gets implicitly flattened into the infinite stream you want.

提交回复
热议问题