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.”

Problem

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

Solution

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

package com.acme.store {
    class Foo { override def toString = "I am com.acme.store.Foo" }
}

The canonical name of the class is com.acme.store.Foo. It’s just as though you declared the code like this:

package com.acme.store
class Foo { override def toString = "I am com.acme.store.Foo" }

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 com.alvinalexander.foo {
   class Foo { override def toString = "I am com.alvinalexander.foo.Foo" }
}

Discussion

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

package foo.bar.baz
class Foo {
    override def toString = "I'm foo.bar.baz.Foo"
}

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.