How does '20 seconds' work in Scala?

ScalaDuration

Scala Problem Overview


How does the following compile:

import scala.concurrent.duration._

val time = 20 seconds

What is actually going on here?

Scala Solutions


Solution 1 - Scala

There are a few things going on.

First, Scala allows dots and parens to be omitted from many method calls, so 20 seconds is equivalent to 20.seconds()*.

Second, an "implicit conversion" is applied. Since 20 is an Int and Int has no seconds method, the compiler searches for an implicit conversion that takes an Int and returns something that does have a seconds method, with the search constrained by the scope of your method call.

You have imported DurationInt into your scope. Since DurationInt is an implicit class with an Int parameter, its constructor defines an implicit Int => DurationInt conversion. DurationInt has a seconds method, so it satisfies all the search criteria. Therefore, the compiler rewrites your call as new DurationInt(20).seconds**.

*I mean this loosely. 20.seconds() is actually invalid because the seconds method has no parameter list and therefore the parens must be omitted on the method call.

**Actually, this isn't quite true because DurationInt is a value class, so the compiler will avoid wrapping the integer if possible.

Solution 2 - Scala

The "magic" that's going on there is called "implicit conversion". You are importing the implicit conversions, and some of them handle the conversion between Int (and Double) to Duration. That's what's you are dealing with.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionripper234View Question on Stackoverflow
Solution 1 - ScalaAaron NovstrupView Answer on Stackoverflow
Solution 2 - ScalaBruno ReisView Answer on Stackoverflow