Another tour of Scala

 
 
 
 

Inner Classes

Viewing old version edf1e3011ed0b0dcb6436afbc64f6c80a837e365; View Current

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 #:


Last Updated 07/25/2009 at 04:49:50 PM by davec

blog comments powered by Disqus