Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala import statement at top and inside scala class

Tags:

scala

In scala what is the difference between these two import strategies

Option 1

import com.somepackage

class MyClass {
  //further code
}

Option 2

class MyClass {
  import com.somepackage
  //further code
}
like image 653
Kalher Avatar asked Jun 10 '13 17:06

Kalher


1 Answers

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

In the first case, the scope is the file, so, imports will be visible in the entire file, but not in other files. In the second case, the scope is the class, so imports will be visible in the entire class, but not in other classes even in the same file (except of course classes nested within MyClass).

You can also limit the scope of an import just to a single method an even a single block(!)

class Foo {
  def bar {
    // do something
    {
      import baz.quux.Frotz
      // use Frotz
    }
    // Frotz not visible here
  }
}

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.

like image 122
Jörg W Mittag Avatar answered Sep 21 '22 20:09

Jörg W Mittag