Static inner classes in scala

oxbow_lakes picture oxbow_lakes · Jul 1, 2009 · Viewed 18.4k times · Source

What is the analog in Scala of doing this in Java:

public class Outer {
  private Inner inner;

  public static class Inner {
  }

  public Inner getInner() { return inner; }
}

I specifically want my inner class to not have to have a fully qualified name - i.e. I want Trade.Type, not TradeType. So in Scala I imagined it might be something like:

class Outer(val inner: Inner) {
    object Inner
}

But this doesn't seem to work: my scala Inner just doesn't seem to be visible from outside the Outer class. One solution would of course be:

class Inner
class Outer(val inner: Inner)

Which is OK - but because of the names of my classes, Inner is really the "type" of the Outer and Outer actually has a long name. So:

class SomeHorriblyLongNameType
class SomeHorriblyLongName(myType: SomeHorriblyLongNameType)

Which is verbose and horrible. I could replace SomeHorriblyLongNameType with just Type but there would then be no obvious connection between it and the class it was related to. Phew

Answer

agilefall picture agilefall · Jul 1, 2009

You can do something like this if don't need access to the outer class in the inner class (which you wouldn't have in Java given that your inner class was declared static):

object A{
    class B {
        val x = 3
    }
}
class A {
    // implementation of class here
}
println(new A.B().x)