在 Java、Scala 或通常的任何 JVM 语言中,有一组默认导入的包。例如,Java 会自动导入java.lang
,您无需在 Java 代码文件中执行此操作。
现在我不知道究竟是哪个组件负责这个(编译器?JVM?),但是有没有办法让额外的包甚至默认导入的类?
假设您有一个包定义了您在整个项目中使用的一组实用程序函数(一个示例可以scala.math
在 Scala 中),如果您能够在每个与数学相关的类中跳过它的导入,那就太好了。
在 Java、Scala 或通常的任何 JVM 语言中,有一组默认导入的包。例如,Java 会自动导入java.lang
,您无需在 Java 代码文件中执行此操作。
现在我不知道究竟是哪个组件负责这个(编译器?JVM?),但是有没有办法让额外的包甚至默认导入的类?
假设您有一个包定义了您在整个项目中使用的一组实用程序函数(一个示例可以scala.math
在 Scala 中),如果您能够在每个与数学相关的类中跳过它的导入,那就太好了。
Scala,从 2.8 开始,具有包对象,其内容会自动导入到包的每个文件中。在包的顶层目录中创建一个名为 package.scala 的文件(例如x/y/z/mypackage
),然后放入其中
package x.y.z
package object mypackage {
...
}
然后包对象中的任何定义都会自动导入(即不需要导入语句)到包 xyzmypackage 中的任何文件中
你可以看看 Scala 源代码——做一个 find dir -name package.scala——它们有很多,最上面定义了 scala 包本身的隐式导入,它们会自动导入到每个 scala 源文件中.
Jim Balter mentions in his answer (go upvote it) the Scala 2.8 package object.
Any kind of definition that you can put inside a class, you can also put at the top level of a package. If you have some helper method you'd like to be in scope for an entire package, go ahead and put it right at the top level of the package.
To do so, put the definitions in a package object. Each package is allowed to have one package object
Scala actually has its own scala package object.
See "Where to put package objects".
So package object can solve the problem of explicit import for a given package, but not for any package.
Its current limitations include:
- First, you cannot define or inherit overloaded methods in package objects.
- Second, you cannot define or inherit a member in a package object which is also the name of a top-level class or object in same package.
We expect that some future Scala release will drop these restrictions.
Original answer:
On the Scala side, a question like "should Scala import scala.collection.JavaConversions._ by default?" shows that you cannot just add default imports as a Scala user.
It has to be supported by the language.
By the way, the conclusion was:
From a Scala expert perspective: Let's keep things simple and limit the implicits that are imported by default to the absolute minimum.
Heiko Seeberger
Raphael does comment though:
I guess you could write your own compiler plugin to add some packages?
And sure enough, this Scala article describe how to extend the Scala compiler.
But the main additions supported are:
- You can add a phase to the compiler, thus adding extra checks or extra tree rewrites that apply after type checking has finished.
- You can tell the compiler type-checking information about an annotation that is intended to be applied to types.
So even with a tree rewrite (including additional imports), I am not sure said rewrite would be done in time for the types and functions (referenced by the implicit imports you are asking for) can be correctly analyzed.
But maybe the Scala Compiler Corner has more ideas on that.
Java 语言规范 (7.5.5)java.lang
中指定了所有类的默认导入
所有其他类都必须使用 import 语句导入。
在 Java 中没有办法做到这一点。