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. E.g. 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.
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