Ok, I’ll explain why I ask this question. I begin to read Lift 2.2 source code these days.
It’s good if you happened to read lift source code before.
In Lift, I found that, define inner class and inner trait are very heavily used.
object Menu has 2 inner traits and 4 inner classes. object Loc has 18 inner classes, 5 inner traits, 7 inner objects.
There’re tons of codes write like this. I wanna to know why the author write like this.
- Is it because it’s the author’s
personal taste or a powerful use of
language feature? - Is there any trade-off for this kind
of usage?
Before 2.8, you had to choose between packages and objects. The problem with packages is that they cannot contain methods or vals on their own. So you have to put all those inside another object, which can get awkward. Observe:
Now you can
import Encrypt._and gain access to the methodencryptIntas well as the classEncryptIterator. Handy!In contrast,
It’s not a huge difference, but it makes the user import both
encrypt._andencrypt.Encrypt._or have to keep writingEncrypt.encryptIntover and over. Why not just use an object instead, as in the first pattern? (There’s really no performance penalty, since nested classes aren’t actually Java inner classes under the hood; they’re just regular classes as far as the JVM knows, but with fancy names that tell you that they’re nested.)In 2.8, you can have your cake and eat it too: call the thing a package object, and the compiler will rewrite the code for you so it actually looks like the second example under the hood (except the object
Encryptis actually calledpackageinternally), but behaves like the first example in terms of namespace–the vals and defs are right there without needing an extra import.Thus, projects that were started pre-2.8 often use objects to enclose lots of stuff as if they were a package. Post-2.8, one of the main motivations has been removed. (But just to be clear, using an object still doesn’t hurt; it’s more that it’s conceptually misleading than that it has a negative impact on performance or whatnot.)
(P.S. Please, please don’t try to actually encrypt anything that way except as an example or a joke!)