Skip to content

Instantly share code, notes, and snippets.

@yawaramin
Last active September 24, 2018 18:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yawaramin/f39b109a1acc9b8263ab38259cbf88f5 to your computer and use it in GitHub Desktop.
Save yawaramin/f39b109a1acc9b8263ab38259cbf88f5 to your computer and use it in GitHub Desktop.
Local imports in Scala

Local imports in Scala

https://github.com/ghik/opinionated-scala/wiki/Packages-and-imports#local-imports

Local imports are very nice tool to minimize the impact of your imports and protect yourself from accidentally polluting too wide namespaces with imports that you need only in small, local context. That's especially important when using wildcard imports (see later).

Cay Horstmann, Scala for the Impatient, §7.8 (Imports can be anywhere)

In Scala, an import statement can be anywhere, not just at the top of a file.

This is a very useful feature, particularly with wildcard imports. It is always a bit worrisome to import lots of names from different sources. In fact, some Java programmers dislike wildcard imports so much that they never use them, but let their IDE generate long lists of imported classes.

By putting the imports where they are needed, you can greatly reduce the potential for conflicts.

https://stackoverflow.com/a/17034405/20371

In Scala, imports are lexically scoped. imported identifiers are only visible within the scope they were imported in.

This is a nice example of Scala's regularity, orthogonality and simplicity. E.g. in Java, blocks create scopes for local variables but not for imports (or methods or anything else). In Scala, blocks create scopes. Period. No exceptions, no corner cases.

The import sits in between the curly braces, ergo it is only visible between the curly braces. It just does what you expect.

https://groups.google.com/d/msg/scala-user/as_riGt3QIQ/bUDzkIhdwYAJ

Problem is that most IDEs for scalas do not handle the import stuff too well. One thing I find important for imports is to keep their scope as tight as possible to prevent accidental implicit inclusion.

Josh Suereth (sbt lead dev): https://groups.google.com/d/msg/scala-user/as_riGt3QIQ/EiRWA5oTChQJ

Try to limit the scope of imported implicits. If one is needed for an entire file, place it at the top, otherwise try to limit it to the scope where it's used. Best, is to find a way to associate an implicit with the types it works with, via companion objects or package objects.

https://www.jetbrains.com/help/idea/managing-imports-in-scala.html#import_settings

IntelliJ IDEA settings > Editor > Code Style > Scala > Imports > Add import statement in closest block

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment