I want to group a set of similar functions in a library in scala. Here are two approaches I have seen elsewhere. I want to understand the differences between the two.
// 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 = { ... }
}
As far as I can tell, the first approach will require explicitly importing
the functions
object whenever you want to use its functions. While the package object approach allows anything in the package functions
to access those methods without importing them.
Ie, com.example.toplevel.functions.MyClass
would have access to com.example.toplevel.functions.foo
implicitly.
Is my understanding correct?
If there are no classes defined within com.example.toplevel.functions
,
it seems the approaches would be equivalent, is this correct?
Ansered by terminally-chill in a comment:
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.