Converting Java to Scala durations
Is there an elegant way to convert java.time.Duration to scala.concurrent.duration.FiniteDuration?
I am trying to do the following simple use of Config in Scala:
val d = ConfigFactory.load().getDuration("application.someTimeout")
However I don't see any simple way to use the result in Scala. Certainly hope the good people of Typesafe didn't expect me to do this:
Edit: Note the line has a bug, which proves the point. See the selected answer below.
I don't know whether an explicit conversion is the only way, but if you want to do it right
toNanos will return the total duration, while getNano will only the nanoseconds component, which is not what you want.
import java.time.Duration import jata.time.temporal.ChronoUnit Duration.of(1, ChronoUnit.HOURS).getNano // 0 Duration.of(1, ChronoUnit.HOURS).toNanos // 3600000000000L
That being said, you can also roll your own implicit conversion
implicit def asFiniteDuration(d: java.time.Duration) = scala.concurrent.duration.Duration.fromNanos(d.toNanos)
and when you have it in scope:
val d: FiniteDuration = ConfigFactory.load().getDuration("application.someTimeout")