# Pre-SIP: Reference-able Package Objects

**URL:** <https://contributors.scala-lang.org/t/pre-sip-reference-able-package-objects/6939>\
**Category:** Scala Improvement Process\
**Created:** [November 23, 2024, 12:43am UTC](https://contributors.scala-lang.org/t/pre-sip-reference-able-package-objects/6939 "2024-11-23T00:43:47Z")\
**Posts on this page:** 9\
**Page:** 1

<div class="post-metadata">

**Author:** ![lihaoyi](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/lihaoyi/32/103_2.png) [@lihaoyi](https://contributors.scala-lang.org/u/lihaoyi)\
**Post date:** [November 23, 2024, 12:43am UTC](https://contributors.scala-lang.org/t/pre-sip-reference-able-package-objects/6939/1 "2024-11-23T00:43:47Z")

</div>

# Reference-able Package Objects

One limitation with `package object`s is that we cannot currently assign them to values: `a.b` fails to compile when `b` is a `package object`, even though it succeeds when `b` is a normal `object`. The workaround is to call `a.b.package`, which is ugly and non-obvious, or to use a normal `object`, which is not always possible. This proposal is to allow `a.b` to automatically expand into `a.b.package` when `b` is a `package object`. Such usage will simplify the language, simplify IDE support for the language, and generally make things more uniform and regular.

## Why?

`package object`s are the natural “entry point” of a package. While top-level declarations reduce their need somewhat, they do not replace it: `package object`s are still necessary for adding package-level documentation or having the package-level API inherit from traits or classes. Other languages have equivalent constructs (`module-info.java` or ` __init__.py`) that fulfil the same need, so it’s not just a quirk of the Scala language.

Notably, normal `object`s are not a replacement for `package object`s, because only `package object`s allow the package contents to be defined in other files. Normal `object`s would require that the package contents be all defined in a single file in the `object` body, or scattered into other files as `trait`s in _different_ `package`s and mixed into the `object`, both of which are messy and sub-optimal.

It’s possible to have a convention _“the `object` named `foo` is always going to be the primary entrypoint for a package”_, but that is just a poor-man’s `package object` with worse syntax and less standardization.

Many libraries use package objects to expose the “facade” of the package hierarchy:

- Mill uses `package object`s to expose the build definitions within each `package`, and each one is an instance of `mill.Module`

- Requests-Scala uses a `package object` to represent the default `requests.BaseSession` instance with the default configuration for people to use

- PPrint uses a `package object` to expose the `pprint.log` and other APIs for people to use directly, as a default instance of `PPrinter`

- OS-Lib uses a `package object` to expose the primary API of the `os.*` operations

None of these use cases can be satisfied by normal `object`s or by top-level declarations, due to the necessity of documentation and inheritance. They need to be `package object`s.

However, the fact that you cannot easily pass around these default instances as values e.g. `val x: PPrinter = pprint` without calling `pprint.package` is a source of friction.

This source of friction is not just for humans, but for tools as well. For example, IntelliJ needs a special case and special handling in the Scala plugin specifically to support this irregularity:

- Original irregularity [intellij-scala/scala/scala-impl/src/org/jetbrains/plugins/scala/lang/psi/impl/expr/ScReferenceExpressionImpl.scala at idea242.x · JetBrains/intellij-scala · GitHub](https://github.com/JetBrains/intellij-scala/blob/idea242.x/scala/scala-impl/src/org/jetbrains/plugins/scala/lang/psi/impl/expr/ScReferenceExpressionImpl.scala#L198)
- Special casing to support Mill, which allows references to package objects [Fix SCL-23198: Direct references to package objects should be allowed in `.mill` files by lihaoyi · Pull Request #672 · JetBrains/intellij-scala · GitHub](https://github.com/JetBrains/intellij-scala/pull/672)

## What

This proposal is meant to allow the following:

```scala
package a
package object b

val z = a.b // Currently fails with "package is not a value"

```

Currently the workaround is to use a `.package` suffix:

```scala
val z = a.b.`package`

```

This proposal is to make it such that given `a.b`, if `b` is a `package` containing a `package object`, expands to `a.b.package` automatically

## Limitations

- `a.b` only expands to `a.b.package` when used “standalone”, i.e. not when part of a larger select chain `a.b.c` or equivalent postfix expression `a.b c`, prefix expression `!a.b`, or infix expression `a.b c d`.

- `a.b` expands to `a.b.package` of the type `a.b.package.type`, and only contains the contents of the `package object`. It does not contain other things in the `package` `a.b` that are outside of the `package object`

Both these requirements are necessary for backwards compatibility, and anyway do not impact the main goal of removing the irregularity between `package object`s and normal `object`s.

## Alternatives

The two main alternatives now are to use `.package` suffixes, e.g. in Mill writing:

```scala
def moduleDeps = Seq(foo.`package`, bar.`package`, qux.baz.`package`)

```

Or to use normal `object`s. Notably, normal `object`s do not allow `package`s of the same name, which leads to contortions. e.g. Rather than:

```scala
package object foo extends _root_.foo.bar.Qux{
  val bar = 1
}

```

```scala
package foo.bar
class Qux

```

We need to move the `package foo` contents into `package foo2` to avoid conflicts with `object foo`, and then we need to add back aliases to all the declarations in `foo2` to make them available in `foo`:

```scala
object foo extends foo2.bar.Qux{
  val bar = 1
  object bar{
    type Qux = foo2.bar.Qux
  }
}

```

```scala
package foo2.bar
class Qux

```

Both of these workarounds are awkward and non-idiomatic, but are necessary due to current limitations in referencing `package object`s directly

## Implementations

Mill since version 0.12.0 already emulates this proposed behavior in Scala 2 using source-code mangling hacks, with custom support in IntelliJ. It works great and does what it was intended to do (allow passing around `package object`s as values without having to call `.package` every time)

We have a prototype Scala3 implementation here [Expand value references to packages to their underlying package objects by odersky · Pull Request #22011 · scala/scala3 · GitHub](https://github.com/scala/scala3/pull/22011)

---

<div class="post-metadata">

**Author:** ![OndrejSpanel](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/ondrejspanel/32/1238_2.png) [@OndrejSpanel](https://contributors.scala-lang.org/u/OndrejSpanel)\
**Post date:** [November 23, 2024, 6:45am UTC](https://contributors.scala-lang.org/t/pre-sip-reference-able-package-objects/6939/2 "2024-11-23T06:45:51Z")

</div>

> [@lihaoyi](#):
>
> One limitation with `package object`s

This is what I read in Scala 3 docs:

[https://docs.scala-lang.org/scala3/reference/dropped-features/package-objects.html](https://docs.scala-lang.org/scala3/reference/dropped-features/package-objects.html)

> will be dropped. They are still available, but will be deprecated and removed at some point in the future

While I like package objects in theory, I remember when using them with Scala 2 I have encountered so many implementation glitches, esp. in the compiler, but in other tooling as well, than I have learned to avoid them as a plague.

I understand you like to keep them (e.g. [Plan for Package Objects in Scala 3](https://contributors.scala-lang.org/t/plan-for-package-objects-in-scala-3/6749)). If it possible to implement them in a way which is glitchless, I am all for it, but considering backwards compatibility burden, I really doubt it it possible (and I have not seen much interest from other relevant people involved).

---

<div class="post-metadata">

**Author:** ![som-snytt](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/som-snytt/32/595_2.png) [@som-snytt](https://contributors.scala-lang.org/u/som-snytt)\
**Post date:** [November 23, 2024, 7:58am UTC](https://contributors.scala-lang.org/t/pre-sip-reference-able-package-objects/6939/3 "2024-11-23T07:58:42Z")

</div>

Scala is the language of second chances for any feature who is down and out.

It would be nice if they just got rid of the backticks in the selection, since we’re so soft on soft keywords, `package` is a natural, see how naturally I put it in backticks for this post.

And it would be nice if they sorted out “my package object has a class C and so does my package!” as we hear on daytime talk shows where people confess their strangely intertwined relations.

Far from going extinct, package objects named after files have overrun the ecosystem, so what’s one more package object named after the package?

Loving inheritance is a bit surprising, because a few years ago, that was the most pernicious of behaviors, but hey, love the one you’re with.

---

<div class="post-metadata">

**Author:** ![odersky](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/odersky/32/42_2.png) [@odersky](https://contributors.scala-lang.org/u/odersky)\
**Post date:** [November 23, 2024, 10:13am UTC](https://contributors.scala-lang.org/t/pre-sip-reference-able-package-objects/6939/4 "2024-11-23T10:13:22Z")

</div>

> [@OndrejSpanel](#):
>
> While I like package objects in theory, I remember when using them with Scala 2 I have encountered so many implementation glitches, esp. in the compiler, but in other tooling as well, than I have learned to avoid them as a plague.

The Scala 3 compiler treats package objects and toplevel definitions mostly in the same way. So the added overhead of package objects is very low, in both spec and implementation. I am not sure what problems were encountered in Scala 2, but it would be good to check each of them whether they still persist in Scala 3.

About dropping package objects: Yes, that was the original intention. But since we still don’t have good alternative solutions to the points mentioned in [Plan for Package Objects in Scala 3](https://contributors.scala-lang.org/t/plan-for-package-objects-in-scala-3/6749) it seems the best way forward is to keep them.

For instance, the concern how to document a package requires a solution where there is one specific artefact standing for a package. We have package objects, and moving to something else would be painful.

---

<div class="post-metadata">

**Author:** ![odersky](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/odersky/32/42_2.png) [@odersky](https://contributors.scala-lang.org/u/odersky)\
**Post date:** [November 23, 2024, 10:22am UTC](https://contributors.scala-lang.org/t/pre-sip-reference-able-package-objects/6939/5 "2024-11-23T10:22:41Z")

</div>

> [@lihaoyi](#):
>
> Currently the workaround is to use a `.package` suffix:
> 
> ```auto
> val z = a.b.`package`
> 
> ```

For me that observation convinced me that the change is right.

```auto
a.b.`package`

```

is an encoding of a package object reference. We should not be forced to drop down to the level of encodings to express that; there should be a way to do it using higher-level concepts.

---

<div class="post-metadata">

**Author:** ![OndrejSpanel](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/ondrejspanel/32/1238_2.png) [@OndrejSpanel](https://contributors.scala-lang.org/u/OndrejSpanel)\
**Post date:** [November 23, 2024, 3:25pm UTC](https://contributors.scala-lang.org/t/pre-sip-reference-able-package-objects/6939/6 "2024-11-23T15:25:04Z")

</div>

> [@odersky](#):
>
> I am not sure what problems were encountered in Scala 2

> <https://github.com/scala/bug/issues/12544>
>
> \## Reproduction steps
> 
> I do not have a small repro yet, the issue is reproduci…ble in my complex project.
> 
> \## Problem
> 
> When compiling the project, which is using Scala 2.13.8, I get following error:
> 
> \`\`\`
> java.lang.AssertionError: assertion failed: 
> List(object package$EntityInScene, object package$EntityInScene)
> while compiling: W:\\Tempi\\threeJVM\\src\\test\\scala\\net\\gamatron\\procas\\game\\state\\AbstractStateTest.scala
> during phase: globalPhase=mixin, enteringPhase=cleanup
> \`\`\`
> 
> The call-stack for the assertion seems to be:
> 
> \`\`\`
> scala.reflect.internal.SymbolTable.throwAssertionError(SymbolTable.scala:171)
> scala.reflect.internal.Symbols$Symbol.suchThat(Symbols.scala:2040)
> scala.reflect.internal.Symbols$ClassSymbol.companionModule0(Symbols.scala:3391)
> scala.reflect.internal.Symbols$ClassSymbol.companionSymbol(Symbols.scala:3394)
> scala.tools.nsc.typechecker.Namers.companionSymbolOf(Namers.scala:2180)
> scala.tools.nsc.typechecker.Namers.companionSymbolOf$(Namers.scala:2171)
> scala.tools.nsc.transform.Erasure.companionSymbolOf(Erasure.scala:23)
> scala.tools.nsc.typechecker.Namers.linkedClassOfClassOf(Namers.scala:2190)
> scala.tools.nsc.typechecker.Namers.linkedClassOfClassOf$(Namers.scala:2186)
> scala.tools.nsc.transform.Erasure.linkedClassOfClassOf(Erasure.scala:23)
> scala.tools.nsc.typechecker.Contexts$Context.accessWithinLinked$1(Contexts.scala:910)
> scala.tools.nsc.typechecker.Contexts$Context.isAccessible(Contexts.scala:965)
> scala.tools.nsc.typechecker.Infer$Inferencer.$anonfun$checkAccessible$1(Infer.scala:289)
> scala.tools.nsc.typechecker.Infer$Inferencer.$anonfun$checkAccessible$1$adapted(Infer.scala:289)
> scala.reflect.internal.Symbols$Symbol.filter(Symbols.scala:2035)
> scala.tools.nsc.typechecker.Infer$Inferencer.accessible$1(Infer.scala:289)
> scala.tools.nsc.typechecker.Infer$Inferencer.checkAccessible(Infer.scala:298)
> scala.tools.nsc.typechecker.Typers$Typer.makeAccessible(Typers.scala:577)
> scala.tools.nsc.typechecker.Typers$Typer.$anonfun$typed1$62(Typers.scala:5343)
> scala.tools.nsc.typechecker.Typers$Typer.silent(Typers.scala:712)
> scala.tools.nsc.typechecker.Typers$Typer.typedSelect$1(Typers.scala:5343)
> scala.tools.nsc.typechecker.Typers$Typer.typedSelectOrSuperCall$1(Typers.scala:5411)
> scala.tools.nsc.typechecker.Typers$Typer.typed1(Typers.scala:5986)
> scala.tools.nsc.transform.Erasure$Eraser.typed1(Erasure.scala:806)
> scala.tools.nsc.typechecker.Typers$Typer.typed(Typers.scala:6041)
> scala.tools.nsc.typechecker.Typers$Typer.$anonfun$typed1$41(Typers.scala:5074)
> scala.tools.nsc.typechecker.Typers$Typer.silent(Typers.scala:698)
> scala.tools.nsc.typechecker.Typers$Typer.normalTypedApply$1(Typers.scala:5076)
> scala.tools.nsc.typechecker.Typers$Typer.typedApply$1(Typers.scala:5104)
> scala.tools.nsc.typechecker.Typers$Typer.typed1(Typers.scala:5985)
> scala.tools.nsc.transform.Erasure$Eraser.typed1(Erasure.scala:806)
> scala.tools.nsc.typechecker.Typers$Typer.typed(Typers.scala:6041)
> scala.tools.nsc.typechecker.Typers$Typer.typedDefDef(Typers.scala:6318)
> scala.tools.nsc.typechecker.Typers$Typer.typed1(Typers.scala:5950)
> scala.tools.nsc.transform.Erasure$Eraser.typed1(Erasure.scala:806)
> 
> ...
> \`\`\`
> 
> For the error to happen I need to use a source similar to (but much more complex):
> 
> \`\`\`
> package object foo {
> 
> trait Foo {
> def f(x: Double): String
> }
> 
> object Foo {
> trait FooA extends Foo {
> def f(x: Double): String = x.toString
> }
> trait FooB extends Foo {
> def f(x: Double): String = x.toInt.toString
> }
> }
> 
> case class BarB() extends Foo with Foo.FooB
> case class BarA() extends Foo with Foo.FooA
> }
> \`\`\`
> 
> Once I move \`FooA\` and \`FooB\` out of the the \`Foo\` companion, everything works fine.
> 
> 
> Does this ring the bell for anyone? Is it worth spending an effort creating a proper repro?

More recently zinc issues with them:

> <https://github.com/sbt/zinc/issues/1396#issuecomment-2356484473>
>
> \## steps
> 
> I am afraid I need help to reproduce the issue in a smaller project.… My project is SBT based, Scala 3, several modules, JS + JVM, with about 500 Scala source files.
> 
> \## problem
> 
> When I make a small change in my project, like renaming a local variable in a function, a lot of files (\>400) is compiled.
> 
> \## expectation
> 
> On any change which is internal to a single function and does not affect its interface (parameters or return value) only one file should be compiled.
> 
> \## notes
> 
> It is possible something in my sources is contributing to the problem, but given current tools, it is quite hard to learn what exactly is the issue. The complete build log obtained using \`Level.Debug\` has over 50 000 lines.
> 
> I attach an excerpt obtained using \`ThisBuild / logLevel := Level.Debug\` from my sbt build which was triggered after I renamed a local variable from \`add\` to \`toAdd\` :
> 
> \`\`\`
> \[debug\] compilation cycle 1
> \[info\] compiling 2 Scala sources to C:\\Dev\\tempi\\jvmCommon\\target\\scala-3.5.0\\classes ...
> 
> \[debug\] compilation cycle 2
> \[info\] compiling 36 Scala sources to C:\\Dev\\tempi\\jvmCommon\\target\\scala-3.5.0\\classes ...
> 
> \[debug\] compilation cycle 3
> \[info\] compiling 50 Scala sources to C:\\Dev\\tempi\\jvmCommon\\target\\scala-3.5.0\\classes ...
> 
> \[debug\] compilation cycle 4
> \[info\] compiling 481 Scala sources and 9 Java sources to C:\\Dev\\tempi\\jvmCommon\\target\\scala-3.5.0\\classes ...
> 
> \`\`\`

As I said, theoretically I like them, but my practical experience with them is not encouraging, too many issues which make work harder. If they are fixable, great - however they need to be reliable, and work well even for complex real-life code, not only for simple examples.

---

<div class="post-metadata">

**Author:** ![odersky](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/odersky/32/42_2.png) [@odersky](https://contributors.scala-lang.org/u/odersky)\
**Post date:** [November 23, 2024, 4:45pm UTC](https://contributors.scala-lang.org/t/pre-sip-reference-able-package-objects/6939/7 "2024-11-23T16:45:57Z")

</div>

Without a self-contained minimization it’s impossible to see whether they would be issues in Scala 3. I have not seen anything out of the ordinary in the example code you gave. The companion symbol logic which failed in the first issue has been made much more robust in Scala 3. So I don’t forsee a problem from that side.

---

<div class="post-metadata">

**Author:** ![lihaoyi](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/lihaoyi/32/103_2.png) [@lihaoyi](https://contributors.scala-lang.org/u/lihaoyi)\
**Post date:** [December 14, 2024, 2:40am UTC](https://contributors.scala-lang.org/t/pre-sip-reference-able-package-objects/6939/8 "2024-12-14T02:40:41Z")

</div>

Opened a SIP [SIP-XX: Reference-able Package Objects by lihaoyi · Pull Request #100 · scala/improvement-proposals · GitHub](https://github.com/scala/improvement-proposals/pull/100)

---

<div class="post-metadata">

**Author:** ![lolgab](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/lolgab/32/3264_2.png) [@lolgab](https://contributors.scala-lang.org/u/lolgab)\
**Post date:** [March 19, 2025, 10:37am UTC](https://contributors.scala-lang.org/t/pre-sip-reference-able-package-objects/6939/9 "2025-03-19T10:37:46Z")

</div>

About the motivation that `package object`s are necessary to use inheritance and top-level fields are not enough.

Can’t the inheritance problem in the top-level fields be solved with `export`s?

```scala
package a.b

trait Foo {
  def foo = "Foo"
  var bar = 1

  val zoo = "zoo"
}

private object StuffToExport extends Foo
export StuffToExport.*

```

Should be equivalent to:

```scala
package a.b

trait Foo {
  def foo = "Foo"
  var bar = 1

  val zoo = "zoo"
}

```

and

```scala
package a

package object b extends Foo

```

If it’s equivalent, I think it should be removed from the motivations since it can’t be a reason to stop deprecating `package object`s

Also `export`s have the advantage that can be used multiple times to export fields from multiple objects, while you can have only one `package object`, which is not consistent with the fact that you can have top-level definitions from multiple files.
