I am using the Akka scheduler in order to stagger the sending of messages from a List, built from reading in lines of a file. Here's some code:
def startClock {
val filename = "conf/my_file.json"
val lines = scala.io.Source.fromFile(filename).getLines.toList
var linePtr = 0
if(linePtr == lines.length) {
clock.cancel()
}
else {
Logger.info(s"num: $linePtr")
default ! Message(lines(linePtr))
linePtr = linePtr + 1
}
}
lazy val clock: Cancellable = Akka.system.scheduler.schedule(Duration.Zero, Duration.create(5000, TimeUnit.MILLISECONDS))(startClock)
val x = clock
Now in order to get around the forward reference compiler error, which looked like the following: play.PlayExceptions$CompilationException: Compilation error[forward reference extends over definition of value clock]
I had to set clock to lazy
and then reference it on the next line in order to trigger startClock
, and it does that part just fine. The issue I have here is, linePtr
is always 0
. It is never incrementing yet the the code in the else {}
block is confirmed always hitting. I essentially just have infinite recursion here and I'm not familiar enough with Scala to identify what I did wrong here. I've also tried defining the val clock
before startClock
but then I have a forward reference in the inverse scenario as well. Seems like a chick and egg problem here.
Maybe the lesson is not about how variable capture works, but about using API. Since getLines
gives you an iterator, just use it to iterate. Speculatively:
val lines = Source.fromFile(f).getLines
val clock = scheduler schedule send
def send = if (lines.hasNext) d ! Message(lines.next) else clock.cancel()
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments