Lucas Lucas - 28 days ago 16
Scala Question

Are within codeblock imports costly in scala

Sometimes it is convenient and clearer to use

import
statements to access multiple elements of an object.

For example, the code

x.y.z.a = 1
x.y.z.b = 2
x.y.z.c = 3


can be written as

{
import x.y.z._

a = 1
b = 2
c = 3
}


obviously it is much more useful when the names are longer.

Is all the work done at compile time, or is the import statement executed at runtime in some way? Is there any cost, in efficiency or otherwise, to using this style?

Answer

Yes, all names and implicits are resolved at compile time, and import doesn't affect anything else.

Of course, what gets executed is still

x.y.z.a = 1
x.y.z.b = 2
x.y.z.c = 3

so you'll fetch x.y.z 3 times (in this example). If z is

package x.y
object z { ... }

this is again just name resolution; but if instead you have something like

object x {
  val y = ... // some type which has val z
}

it's 2 method calls each time and putting z into a local variable performs better (but JIT may optimize this if this code runs often enough).