我想在 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/