添加默认包导入 [英] Adding default package imports

查看:47
本文介绍了添加默认包导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java、Scala 或通常的任何 JVM 语言中,有一组默认导入的包.例如,Java 会自动导入 java.lang,您无需在 Java 代码文件中执行此操作.

In Java, Scala, or generally any JVM language, there is a set of packages that is imported by default. Java, for instance, automatically imports java.lang, you don't need to do it in your Java code file.

现在我不知道究竟是哪个组件负责处理这个问题(编译器?JVM?),但是有没有办法默认导入额外的包甚至类?

Now I don't know which component takes care of this exactly (the compiler? the JVM?), but is there any way to have additional packages or even classes imported by default?

假设您有一个包定义了您在整个项目中使用的一组实用程序函数(例如 Scala 中的 scala.math),如果您能够跳过导入,那就太好了在每个与数学相关的课程中都有它.

Say you have a package defining a set of utility functions you use throughout your project (an example could be scala.math in Scala), it would be great if you were able to skip the import for it in every math related class.

推荐答案

从 2.8 开始,Scala 具有包对象,其内容会自动导入到包的每个文件中.在你的包的顶级目录(例如,x/y/z/mypackage)中创建一个名为 package.scala 的文件,并放入其中

Scala, as of 2.8, has package objects, the contents of which are automatically imported into every file of the package. Create a file called package.scala in the top level directory of your package (e.g., x/y/z/mypackage), and put into it

package x.y.z

package object mypackage {
  ...
}

然后包对象中的任何定义都会自动导入(即不需要导入语句)到包 x.y.z.mypackage 中的任何文件中

Then any definition within the package object is automatically imported (i.e., no import statement is needed) into any file in package x.y.z.mypackage

您可以查看 Scala 源代码 -- 执行 find dir -name package.scala -- 有很多,最顶层定义了 Scala 包本身的隐式导入,它们会自动导入到每个scala 源文件.

You can take a look at the Scala sources -- do a find dir -name package.scala -- there are a bunch of them, the topmost defining the implicit imports for the scala package itself, which are automatically imported into every scala source file.

这篇关于添加默认包导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆