封装对象

发布于 2024-09-12 21:22:27 字数 611 浏览 1 评论 0原文

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

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

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

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

package object _root_ { ... }

是不允许的(这是合理的),

package object x.y { ... }

也是不允许的。

看来包对象必须在直接父包中声明,如果按照上面的方式编写,则需要大括号分隔的包声明形式。

它们常用吗?如果是这样,怎么办?

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 { ... }

is also disallowed.

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

懷念過去 2024-09-19 21:22:27

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

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

// 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._ 时,定义也会被导入。

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

import swing._
import Swing._

才能拥有 onEDT 等所有优点以及来自 的隐式转换Tuple2Dimension

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.

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 = // ...

}

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

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

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

孤独患者 2024-09-19 21:22:27

虽然莫里茨的答案是正确的,但需要注意的另一件事是包对象是对象。除此之外,这意味着您可以使用混合继承从特征构建它们。 Moritz 的示例可以写为

package object bar extends Versioning 
                          with JodaAliases 
                          with JavaAliases {

  // package wide constants:
  override val version = "1.0"

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

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

}

此处版本控制是一个抽象特征,它表示包对象必须具有“版本”方法,而 JodaAliases 和 JavaAliases 是包含方便的类型别名的具体特征。所有这些特征都可以被许多不同的包对象重用。

While Moritz's answer is spot on, one additional thing to note is that package objects are objects. Among other things, this means you can build them up from traits, using mix-in inheritance. Moritz's example could be written as

package object bar extends Versioning 
                          with JodaAliases 
                          with JavaAliases {

  // package wide constants:
  override val version = "1.0"

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

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

}

Here Versioning is an abstract trait, which says that the package object must have a "version" method, while JodaAliases and JavaAliases are concrete traits containing handy type aliases. All of these traits can be reused by many different package objects.

音盲 2024-09-19 21:22:27

包对象的主要用例是当您使用包定义的 API 时,需要在包内部以及包外部的各个位置进行定义。

Scala 3 则不然,计划于 2020 年中期发布,基于 多蒂,如在这里

顶级定义

各种定义都可以写在顶层。
不再需要包对象,将逐步淘汰。

package p 

type Labelled[T] = (String, T) 
val a: Labelled[Int] = ("count", 1) 
def b = a._2 
def hello(name: String) = println(i"hello, $name)

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.

Not so with Scala 3, scheduled to be released mid-2020, based on Dotty, as in here:

Toplevel Definitions

All kinds of definitions can be written on the toplevel.
Package objects are no longer needed, will be phased out.

package p 

type Labelled[T] = (String, T) 
val a: Labelled[Int] = ("count", 1) 
def b = a._2 
def hello(name: String) = println(i"hello, $name)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文