Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala FiniteDuration from String

Tags:

scala

duration

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.

like image 929
user2916547 Avatar asked Nov 12 '15 18:11

user2916547


2 Answers

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.

like image 64
ale64bit Avatar answered Sep 21 '22 09:09

ale64bit


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)

like image 41
Oto Brglez Avatar answered Sep 22 '22 09:09

Oto Brglez