How does '20 seconds' work in 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.


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.

Tags:

Scala

Duration