scalalibrary-design

Scala: package object v.s. singleton object within a package


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.

Singleton object defined in a package

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

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

Package object

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

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

Comparison

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?


Solution

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