Is it possible to parse a String
into a FiniteDuration
in Scala without writing custom code?
There is a method on Duration
, called create
, that accepts a String
, however that produces a Duration
and not sure how to further use it to create a FiniteDuration
from it. There are a few factory methods on Duration
that produce FiniteDuration
instances, but those imply that I have to parse my string to produce their parameters (their signature expect a long and a TimeUnit
).
These types I mention are from scala.concurrent.duration
.
Thank you.
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 collect
ing 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.
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 Duration
s 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With