Scala FiniteDuration from String

Is it possible to parse String in FiniteDuration in Scala without writing special code?

Duration has a Duration method that accepts create , which accepts a String , however it creates a Duration and is not sure how to use it to create a FiniteDuration . There are several factory methods on Duration that produce FiniteDuration instances, but that implies that I have to parse my string to create their parameters (their signature expects long and a TimeUnit ).

These types that I mention are related to scala.concurrent.duration .

Thanks.

+7
scala duration
source share
1 answer

You can use the mentioned method to create a Duration object (or just use the apply method). Then you can check if it is FiniteDuration by collect it (since FiniteDuration is a subtype of Duration ), although there are several options 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 this helped.

+14
source share

All Articles