Scala C# style package syntax (curly brace syntax)

Depending on your personal preference, or perhaps the needs of the moment, you can use a C#-style "curly brace" package syntax in your Scala applications, instead of the usual Java-style. As a quick example of what this looks like, here are a couple of simple package names and classes:

package orderentry {
  class Order
  class LineItem
  class Foo
}

package customers {
  class Customer
  class Address
  class Foo

  package database {
    // this is the "customers.database" package/namespace
    class CustomerDao
    // this Foo is different than customers.Foo or orderentry.Foo
    class Foo
  }
}

In this example I've defined three package namespaces:

  • orderentry
  • customers
  • customers.database

As you can see from the code, I also have three classes named "Foo", and they are different classes in different packages. I have:

  • orderentry.Foo
  • customers.Foo
  • customers.database.Foo

Of course this isn't any different than what you can do in Java, but this "curly brace" package syntax is very different than what you can write in Java, so I wanted to share this alternate syntax.

Packages inside packages

As another simple example, you can include one Scala package inside another using curly braces, like this:

package tests

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

object PackageTests {

  def main(args: Array[String]) {
    // create an instance of our Foo class
    val f = new foo.bar.baz.Foo
    println(f.toString)
  }

}

As you can see, after creating the Foo class in the foo.bar.baz package, we can create an instance of it as usual, like this:

val f = new foo.bar.baz.Foo

I hope these Scala packaging examples have been helpful.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.