How to package Scala code with the “curly braces” style

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 7.1, “How to package Scala code with the ‘curly braces’ style.”


You want to use a nested style package notation in Scala, similar to the namespace notation in C++ and C#.


Wrap one or more classes in a set of curly braces with a package name, as shown in this example:

package {
    class Foo { override def toString = "I am" }

The canonical name of the class is It’s just as though you declared the code like this:

class Foo { override def toString = "I am" }

With this approach, you can place multiple packages in one file. You can also nest packages using this “curly braces” style.

The following example creates three Foo classes, all of which are in different packages, to demonstrate how to include one package inside another:

// a package containing a class named Foo
package orderentry {
    class Foo { override def toString = "I am orderentry.Foo" }

// one package nested inside the other
package customers {
    class Foo { override def toString = "I am customers.Foo" }
    package database {
        // this Foo is different than customers.Foo or orderentry.Foo
        class Foo { override def toString = "I am customers.database.Foo" }

// a simple object to test the packages and classes
object PackageTests extends App {
    println(new orderentry.Foo)
    println(new customers.Foo)
    println(new customers.database.Foo)

If you place this code in a file, and then compile and run it, you’ll get the following output:

I am orderentry.Foo
I am customers.Foo
I am customers.database.Foo

This demonstrates that each Foo class is indeed in a different package.

As shown in the first example, package names don’t have to be limited to just one level. You can define multiple levels of depth at one time:

package {
   class Foo { override def toString = "I am" }


You can create Scala packages with the usual Java practice of declaring a package name at the top of the file:

class Foo {
    override def toString = "I'm"

In most cases, I use this packaging approach, but because Scala code can be much more concise than Java, the alternative curly brace packaging syntax can be very convenient when you want to declare multiple classes and packages in one file.

The Scala Cookbook

This tutorial is sponsored by the Scala Cookbook, which I wrote for O’Reilly:

You can find the Scala Cookbook at these locations:

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.