Scala runs on the JVM, but that doesn’t mean we have to write it like Java. Eclipse discourages use of the default package. What are some considerations (e.g. size of project) that determine how code ought to be packaged in Scala?
6
Scala package best practices are generally the same as Java conventions, according to the Style Guide.
// wrong!
package coolness
// right!
package com.novell.coolness
// right, for package object com.novell.coolness
package com.novell
/**
* Provides classes related to coolness
*/
package object coolness {
}
Packages on the JVM have a very important job – to provide a globally unique namespace for all your classes. It doesn’t matter whether you write your code with Scala or Java or Clojure; in the end all get compiled to .class
files or JAR archives. Note that Scala is not the Anti-Java, instead interoperability with Java was a primary design goal.
So the package naming convention applies not only to Java but essentially to anything that runs on the JVM and wants to interoperate with Java. Using the Domain Name System as a basis for package names allows you to easily register a globally unique namespace for your code.
I’ve written code in enough languages that feature no similar convention, and the name clashes that invariably arise are bloody annoying. Who would have guessed two projects would both publish The One And Only template
system? Clearly no one else could write a better http
client. In particular, the conventions in C++, Python, Perl, and NodeJS are not satisfactory, while Java surprisingly gets this right.
0