Another Tour of Scala


The Gist

Inner Classes describes Scala’s support for defining a class within another class.

My Interpretation

Scala allows inner classes to be defined, which is to say, classes that are declared inside another class. Unlike Java, these classes are not scoped to the containing class, but to the containing object.

Suppose you are modeling a focus group type study. You will have a “study” which describes the thing under observation (e.g. “Do Programmers Like Scala?”) and you will divide your participants into control groups (e.g. Java programmers, Ruby programmers, etc.).

For reasons of encapulsation, you don’t need to expose the representation of your control group class, so you make it inner.

So far, this looks like Java. What if you decide to use multiple studies about programming, and you want another study that studies if programmers like Haskell? You might think to re-use the non-Haskell control groups in your new study, but you can’t:

The compiler error shows you the difference between Scala and Java as far as inner classes go. The type of instances of the ControlGroup within likesScala are different than those used by likesHaskell.

You can make Scala behave like Java in this way, by qualifying the class with a #:

My Thoughts on this Feature

I can see having the option to scope an inner class to an object, but it seems like an odd default. The use of # to delineate the “class scoped” behavior also seems odd.