Edit this page on GitHub

Reference-able Package Objects

This feature is available under -preview since Scala 3.10.0. It is specified in SIP-68.

One limitation with package objects 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`

But this is ugly and non-obvious. Or one could use a normal object, which is not always possible.

This preview feature drops that limitation. It is enabled by the -preview compiler flag.

The feature turns the following into valid code:

package a
package object b

val z = a.b

Without the feature, the workaround is to use a .package suffix:

val z = a.b.`package`

With the feature, a reference such as a.b where 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 objects and normal objects.

In this article