'Scala C# style package syntax (curly brace syntax)'에 해당되는 글 1건

  1. 2014.03.28 Scala C# style package syntax (curly brace syntax)
00.scala2014. 3. 28. 12:57
반응형

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.

Posted by 1010