ripper234 ripper234 - 1 year ago 76
Scala Question

How does '20 seconds' work in Scala?

How does the following compile:

import scala.concurrent.duration._

val time = 20 seconds

What is actually going on here?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download