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
A static inner class is a nested class which is a static member of the outer class. It can be accessed without instantiating the outer class, using other static members. Just like static members, a static nested class does not have access to the instance variables and methods of the outer class.
Non-static nested classes are called inner classes. Nested classes that are declared static are called static nested classes. A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private.
Java static nested class A static class is a class that is created inside a class, is called a static nested class in Java. It cannot access non-static data members and methods. It can be accessed by outer class name. It can access static data members of the outer class, including private.
As we know, Scala does NOT have “static” keyword at all. This is the design decision done by Scala Team. The main reason to take this decision is to make Scala as a Pure Object-Oriented Language. “static” keyword means that we can access that class members without creating an object or without using an object.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With