Library contents

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

  1. Start with 90 seconds
  2. Do this Express in minutes and seconds
  3. Result 1 minute, 30 seconds
Sixty seconds make one full minute and thirty seconds remain.

Syntax

Scala 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.

From the programval budget = 2.minutes
First output line90
Lesson.scala
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)
  }
}
Output
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

Advertisements

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.

Given3750 ms → whole seconds
Worked result3

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.

Given820 ms → whole seconds
Worked result0