使用scala中的yield返回和迭代集合

fbl*_*fbl 5 loops scala yield-keyword yield-return

我在Scala中有一个DateTime和TimeSpan类(假设<和+运算符可以正常工作).我正在尝试定义一个'范围'函数,它采用开始/停止时间和步进的时间跨度.在C#中,我会以收益率来做这件事,我想我应该能够在Scala中做同样的事情......除了我得到一个奇怪的错误.

在'收益率'线上,我得到"非法开始陈述".

  def dateRange(from : DateTime, to : DateTime, step : TimeSpan) =
  {
      // not sure what the list'y way of doing this is
    var t = from

    while(t < to)
    {
      yield t; // error: illegal start of statement
      t = t + step
    }
  }
Run Code Online (Sandbox Code Playgroud)

看看这段代码,我很好奇两件事:1)我做错了什么?2)编写的代码非常必要(使用var t等).在Scala中以更快的速度执行此操作的功能是什么?

谢谢!

Deb*_*ski 17

def dateRange(from : DateTime, to : DateTime, step : TimeSpan): Iterator[DateTime] =
  Iterator.iterate(from)(_ + step).takeWhile(_ <= to)
Run Code Online (Sandbox Code Playgroud)