Another tour of Scala

 
 
 
 

Scala Object

Viewing old version 951e1a38f998041475f5857a020acba82c5baede; View Current

The Gist

The Scala Tour doesn’t officially call out this feature.

My Interpretation

In Scala, classes have no static members (as they can in Java and Ruby). Instead, Scala provides a means to create singleton objects. These are, essentially, global variables (although it is only global to the scope in which it is included via import). However, by judicious use of naming, these objects can make your code more readable, especially with respect to PatternMatching.

In the most basic case, you can use objects as a means to “statically import” methods to avoid full-qualification:

This is pretty much static imports from Java. Note a few things:

  • We can import pretty much anywhere in our code; we don’t need to import for the entire file — this is handy for keeping code comprehensible and reducing data flow
  • This is not canoncial Scala code; you don’t frequently throw exceptions or deal with the option class in this way.

Objects in Scala serve a more complex and important purpose than as an alternate syntax for static imports, however. AdvancedScalaObjects explains this in more detail.


Last Updated 08/20/2009 at 08:34:22 AM by davec

blog comments powered by Disqus