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.