How does '20 seconds' work in Scala?

ripper234 picture ripper234 · Feb 27, 2013 · Viewed 41.4k times · Source

How does the following compile:

import scala.concurrent.duration._

val time = 20 seconds

What is actually going on here?

Answer

Aaron Novstrup picture Aaron Novstrup · Feb 27, 2013

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.