How to create Durations in Scala
Julien Truffaut
6 October 2023
In Scala, we mostly use the Java standard library to represent time, for example:
java.time.Instant
for timestampsjava.time.LocalDate
for calendar dates
One exception is duration, which can be used to specify after how much time a computation should timeout. In this case, we use a class from the Scala standard library called scala.concurrent.duration.Duration
.
The Basic Constructor
Creating a Duration
is straightforward. We can use the apply method, which takes a numeric value (Long) and a time unit from Java’s standard library.
import java.util.concurrent.TimeUnit
import scala.concurrent.duration.Duration
val short = Duration(100, TimeUnit.MILLISECONDS)
val long = Duration(2, TimeUnit.MINUTES)
Leveraging the Duration DSL
Scala makes working with durations even more elegant by offering a DSL (Domain-Specific Language) for creating them using extension methods. To use this DSL, simply import scala.concurrent.duration._
.
import scala.concurrent.duration._
val short = 100.millis
val long = 2.minutes
Durations from Configuration Files
Integrating durations into our Scala application configuration is a breeze, thanks to support from popular Scala configuration libraries such as lightbend/config. We can specify a duration in our configuration files by using the following format: $number space $time_unit.
{
publication_interval = "10 seconds"
}
Finite Duration
It’s important to note that all durations mentioned in this article are actually of type FiniteDuration
. This type is a subtype of Duration
specifically designed for representing durations smaller than 292 years. It’s a good practice to use variables of type FiniteDuration
whenever possible since it’s the preferred type used by most Scala libraries.
In summary, Scala simplifies the process of working with durations by offering both a basic constructor and a convenient DSL. You can easily integrate durations into your configuration files, and it’s advisable to use FiniteDuration when dealing with durations in your code.
Stay tuned for more insightful articles. See you soon!