Reputation: 10303
I encountered the following in Scala code:
class MyClass { ... val a = new A; import a._ }
What does exactly val a = new A; import a._
mean ?
Upvotes: 16
Views: 1105
Reputation: 297175
Let's explain this with something you should be familiar with:
println("Hello world")
The question is: why does that work? There's no object called println
with an apply
method, which is the usual explanation for code that looks like that. Well, as it happens, the above code is really doing this:
Predef.println("Hello world")
In other words, println
is a method on the object scala.Predef
. So, how can you use it like above? Well, like this:
import scala.Predef._
println("Hello world")
Importing the contents of a stable reference (ie, not a var
or a def
) will make its methods available without having to prefix them with reference.
.
It also makes any implicits defined inside it available, which is how the implicit conversions defined inside scala.Predef
are made available as well -- Scala imports the contents of java.lang
, scala
and scala.Predef
(in that order, so the latter ones override the earlier ones).
Upvotes: 7
Reputation: 340733
It means that all methods and variables of a
object of A
type are now available in this block (scope) without explicitly mentioning a
. So if A
has a bar()
method you can now say:
bar()
instead of
a.bar()
but only within the scope where import
is defined.
Upvotes: 9
Reputation: 370132
It imports the methods and variables of the a object. So if you want to call a.foo()
, you can just call foo()
instead.
Upvotes: 15