How does the following compile:
val time = 20 seconds
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
Second, an "implicit conversion" is applied. Since
20 is an
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
*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.