Scala 3: Multiple packages in one file (syntax, examples)

As a brief note today, if you want to have multiple packages and classes in one file in Scala 3, this syntax should do the trick for you:

    class Foo:
        override def toString = "Foo"

    class Bar:
        val foo = Foo()

package com.acme.common:
    @main def multiPackageTest =
        val b = Bar()

In this example:

  • Class Foo is in the package
  • Class Bar is in the package
  • The two import statements show how to import classes from one package into the other

If you prefer, you can also use curly braces when declaring multiple Scala packages in one file.

If this is helpful, know that you can find over 250 other examples that are explained in much more detail in the 2nd Edition of the Scala Cookbook, which was published in August, 2021.