In following scala code:
object Timer
{
def oncePerSecond(callback: () => Unit): Unit =
{
while (true)
{
callback()
Thread.sleep(1000)
}
}
def main(args: Array[String]): Unit =
{
oncePerSecond(() =>
Console.println("Time flies... oh, you get the idea."))
}
}
Is the anonymous function executed first when passed in as a parameter
and then again every second in the loop?
It’s executed as part of this:
so it’ll execute every second, starting from when it’s passed in. It’s only executed in the loop. It wouldn’t be executed normally upon being passed in e.g.
would only execute that method if a particular condition was satisfied.