简体   繁体   中英

Scala import statement at top and inside scala class

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
}

In Scala, import s are lexically scoped. import ed identifiers are only visible within the scope they were import ed in.

In the first case, the scope is the file, so, import s will be visible in the entire file, but not in other files. In the second case, the scope is the class, so import s 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. Eg in Java, blocks create scopes for local variables but not for import s (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.

The difference is:

In Option 1 the import is viable for the complete scope. ie any class/trait/function in com.somePackage can be used anywhere inside/outside the MyClass

But in case of Option 2 it can only be used inside the MyClass and not outside it because scope of import is limited to inside MyClass only.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM