Scala FiniteDuration from String

user2916547 picture user2916547 · Nov 12, 2015 · Viewed 13.2k times · Source

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.

Answer

ale64bit picture ale64bit · Nov 12, 2015

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.