Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static inner classes in scala

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

like image 572
oxbow_lakes Avatar asked Jul 01 '09 16:07

oxbow_lakes


People also ask

What is a static inner class?

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.

Can a static class have an inner 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.

What is the use of static inner class?

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.

Can we have static members in classes in Scala?

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.


1 Answers

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) 
like image 150
agilefall Avatar answered Oct 14 '22 15:10

agilefall