Aries Aries - 1 year ago 68
Scala Question

How to specify a 'next' function in Scala for loop

I have a code snippet like this:

val step = Step.Montyly //this could be Yearly, daily, hourly, etc.
val (lower, upper) = (****, ****) //unix timestamps, which represent a time range
val timeArray = Array[Long](0)

var time = lower
while (time <= upper) {
timeArray +: = time
time = // eg, = time + 3600, = new DateTime(time).addMonths(1).toTimeStamp()

return timeArray

Though this is written in Scala, it is a non-functional way. I'm new to Scala, wondering if this can be rewritten in functional way. I know things like the following:

for(i <- 1 to 10 by step) yield i

But step is a fixed value here, how to make 'i' can be generated by a 'next function' rather than a fixed value?

Answer Source

You'll have to change the flow a bit to make it functional (without mutable Array and without var). Stream.iterate works with an initial start value, and applies a function repeatedly to generate the next elements.

Stream.iterate(lower)( < upper)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download