Scala FiniteDuration from String

If you are using Scala 2.13 or above you can also leverage the isFinite method on Duration object to get Option[FiniteDuration], with the help of Option.when.

This is an example of how to do just that:

val dA: Duration = Duration("Inf")
val dB: Duration = Duration("48 hours")

val a = Option.when(dA.isFinite)(dA.asInstanceOf[FiniteDuration])
val b = Option.when(dB.isFinite)(dB.asInstanceOf[FiniteDuration])

println(a) // -> None
println(b) // -> Some(2 days)

You can also then write implicit conversion that will help you convert all Durations to Option[FiniteDuration] like so...

implicit val durationToFinite: Duration => Option[FiniteDuration] = 
  d => Option.when(d.isFinite)(d.asInstanceOf[FiniteDuration])

val finiteDurationD: Option[FiniteDuration] = Duration("Int")
val finiteDurationE: Option[FiniteDuration] = Duration("48 hours")

println(finiteDurationD) // -> None
println(finiteDurationE) // Some(2 days)


You can use the method you mention in order to create a Duration object (or simply use the apply method). Then, you can check if it's a FiniteDuration by collecting it (since FiniteDuration is a sub-type of Duration), although there are several variants depending on your use case:

scala> val finite = Duration("3 seconds")
scala> val infinite = Duration("Inf")
scala> val fd = Some(finite).collect { case d: FiniteDuration => d }
fd: Option[scala.concurrent.duration.FiniteDuration] = Some(3 seconds)
scala> val id = Some(infinite).collect { case d: FiniteDuration => d }
id: Option[scala.concurrent.duration.FiniteDuration] = None

Hope it helped.

Tags:

Scala

Duration