简体   繁体   中英

What does this import exactly mean in Scala?

I encountered the following in Scala code:

class MyClass {
  ...
  val a = new A; import a._

}

What does exactly val a = new A; import a._ val a = new A; import a._ mean ?

It imports the methods and variables of the a object. So if you want to call a.foo() , you can just call foo() instead.

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.

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).

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