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):
Do those "rules" make sense to you? Am I restricting myself too much?
In Java, the import statement is written directly after the package statement (if it exists) and before the class definition.
Importation in Scala is a mechanism that enables more direct reference of different entities such as packages, classes, objects, instances, fields and methods. The concept of importing the code is more flexible in scala than Java or C++. The import statements can be anywhere.
You need to run console from within the sbt shell. Then, sbt will compile whatever is defined in funsets and automatically add it in your Scala shell. From there, you'll be able to do import funsets. _ .
Packages are declared as a first statement at the top of a Scala file.
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
Put imports at the top of a file.
Having them scattered all over a file makes it harder to read the code:
I see no benefit in placing them next to their closest scope. Actually, with this reasoning in mind, one should never use them at all; instead, one should always use the full namespace for every referenced entity. Does that make any sense? IMHO, no.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With