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:

package com.acme.foo:
    class Foo:
        override def toString = "Foo"

package com.acme.bar:
    import com.acme.foo.Foo
    class Bar:
        val foo = Foo()

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

In this example:

  • Class Foo is in the package com.acme.foo
  • Class Bar is in the package com.acme.bar
  • 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.