包对象 [英] Package objects

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

问题描述

什么是包对象,与其说是概念,不如说是它们的用法?

What are package objects, not so much the concept but their usage?

我试图让一个示例工作,但我工作的唯一形式如下:

I've tried to get an example working and the only form I got to work was as follows:

package object investigations {
    val PackageObjectVal = "A package object val"
}

package investigations {

    object PackageObjectTest {
        def main(args: Array[String]) {
            println("Referencing a package object val: " + PackageObjectVal)
        }
    }
}

到目前为止我所做的观察是:

Observations I've made so far are:

package object _root_ { ... }

被禁止(这是合理的),

is disallowed (which is reasonable),

package object x.y { ... }

也不允许.

似乎必须在直接父包中声明包对象,如果如上编写,则需要大括号分隔的包声明形式.

It seems that a package object must be declared in the immediate parent package and, if written as above, the brace delimited package declaration form is required.

它们是否常用?如果是这样,如何?

Are they in common use? If so, how?

推荐答案

通常,您会将包对象放在它对应的包中名为 package.scala 的单独文件中.您也可以使用嵌套包语法,但这很不寻常.

Normally you would put your package object in a separate file called package.scala in the package that it corresponds to. You can also use the nested package syntax but that is quite unusual.

包对象的主要用例是,当您使用包定义的 API 时,您需要在包内以及包外的各个位置进行定义.下面是一个例子:

The main use case for package objects is when you need definitions in various places inside your package as well as outside the package when you use the API defined by the package. Here is an example:

// file: foo/bar/package.scala

package foo

package object bar {

  // package wide constants:
  def BarVersionString = "1.0"

  // or type aliases
  type StringMap[+T] = Map[String,T]

  // can be used to emulate a package wide import
  // especially useful when wrapping a Java API
  type DateTime = org.joda.time.DateTime

  type JList[T] = java.util.List[T]

  // Define implicits needed to effectively use your API:
  implicit def a2b(a: A): B = // ...

}

现在该包对象内的定义在整个包 foo.bar 中可用.此外,当包外的人导入 foo.bar._ 时,定义会被导入.

Now the definitions inside that package object are available inside the whole package foo.bar. Furthermore the definitions get imported when someone outside of that package imports foo.bar._.

通过这种方式,您可以防止要求 API 客户端发出额外的导入以有效地使用您的库 - 例如在scala-swing中你需要写

This way you can prevent to require the API client to issue additional imports to use your library effectively - e.g. in scala-swing you need to write

import swing._
import Swing._

拥有 onEDT 等所有优点以及从 Tuple2Dimension 的隐式转换.

to have all the goodness like onEDT and implicit conversions from Tuple2 to Dimension.

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

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