Scala: package object v.s. singleton object within a package
Asked Answered
H

1

7

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?

Homologous answered 31/8, 2018 at 17:47 Comment(1)
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.Pontias
H
4

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.

Homologous answered 12/1, 2019 at 17:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.