Vilius Normantas Vilius Normantas - 11 months ago 43
Scala Question

Scala: Where should I place import statements?

Scala allows to import almost whatever you want, wherever you want, and this is great. But are there any considerations I should take into account when importing something inside class, method or just any block? How does it relate to performance, style, maintainability of code, etc?

Generally I try to obey these rules (made up by myself):

  • If I'm importing something external from other package I always place it at the top just after the "package".

  • If I'm using something more than once in the same file, I also import it at the top.

  • Otherwise I place my imports at the top of the relevant class/trait/object.

  • I avoid to import things in methods and blocks.

  • I try to avoid importing contents of instance objects, unless I have a really good reason to do so.

  • I would avoid renaming and "hiding" unless to resolve name collisions, but I have never needed that yet.

Do those "rules" make sense to you? Am I restricting myself too much?

Answer Source

It usually makes sense to restrict the scope of something (e.g. a variable or a method) to the "least" as it is possible. For example, use an inner def as opposed to one at the class level. Why should import statements be any different? Why pollute a class with imports which are only used in a single block?

I like to declare imports as close to where they are used as possible!

The upshot of this is that common utilities, both libraries like scalaz and my own, tend to get imported once at the top-level (because they are used throughout the class). Whereas stuff like I/O gets imported locally, only where it is used