Scala FiniteDuration arithmetic
The scala.concurrent.duration extensions turn numbers into typed time spans. Addition and subtraction combine compatible duration units.
A simple example
FiniteDuration arithmetic
- Start with 90 seconds
- Do this Express in minutes and seconds
- Result 1 minute, 30 seconds
Syntax
val remaining = budget - elapsed
Run this example in Scala
Save the program as Lesson.scala. Use Scala 2.13.
scalac Lesson.scala
scala Lesson
Calculate a retry budget in seconds
A scheduler receives durations in one unit but reports or retries in another. Track the whole units and any fractional part before turning the original delay into a displayed time or retry budget.
import scala.concurrent.duration._
object Lesson {
def main(args: Array[String]): Unit = {
val budget = 2.minutes
val elapsed = 30.seconds
val remaining = budget - elapsed
println(remaining.toSeconds)
println(remaining.toMinutes)
}
}
90 1
toMinutes discards partial minutes. Keep the duration itself until choosing a display unit so a 90-second remainder can still be reported exactly.
Scala documentation for FiniteDuration arithmetic
Time a school animation
A student’s animation runs for 3750 milliseconds. Convert the elapsed milliseconds to complete seconds. Leave the fractional second out of the display.
Time a ticket scan
A fast ticket scan takes 820 milliseconds. Convert the elapsed milliseconds to complete seconds. Leave the fractional second out of the display.