Scala:包对象v.s.包内的单例对象

标签 scala library-design

我想在 Scala 的库中对一组类似的函数进行分组。
这是我在其他地方看到的两种方法。我想了解
两者之间的差异。

包中定义的单例对象

// src/main/scala/com/example/toplevel/functions.scala
package com.example.toplevel

object functions {
  def foo: Unit = { ... }
  def bar: Unit = { ... }
}

包对象

// src/main/scala/com/example/toplevel/package.scala
package com.example.toplevel

package object functions {
  def foo: Unit = { ... }
  def bar: Unit = { ... }
}

比较

据我所知,第一种方法需要明确导入functions任何时候你想使用它的功能的对象。虽然包对象方法允许包中的任何内容 functions访问这些方法而不导入它们。

即,com.example.toplevel.functions.MyClass将有权访问 com.example.toplevel.functions.foo含蓄地。

我的理解正确吗?

如果在 com.example.toplevel.functions 中没有定义类,
似乎这些方法是等效的,这是正确的吗?

最佳答案

由 terminally-chill 在评论中回答:

yes, your understanding is correct. Anything defined in your package object will be available without having to import. If you use an object, you will have to import it even within the same package.

关于Scala:包对象v.s.包内的单例对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52120496/

相关文章:

scala - 为什么不可变对象(immutable对象)支持函数式编程?

scala - 如何关闭akka ActorSystem中的调度程序线程

scala - 将 "_"分配给 Scala 中的字段是什么意思?

java - Apache POI 图像比例图像

java - 如何在 Scala 中查找文件大小?

c++ - 用 C 和 C++ 接口(interface)编写库,用哪种方式包装?

.net - 为什么 .Net 框架没有优先队列类?

c++ - 将函数指针作为 API 接口(interface)传递给已编译的库

c++ - 为什么 C++03 文件流不接受字符串构造函数参数?

.NET 国际奥委会 : Preconfiguring library components for easier use