7.1. Packaging with the Curly Braces Style Notation

Problem

You want to use a nested style package notation, 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 ...

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.