Static inner class vs Companion's inner class

434 views Asked by At

Reading chapter 20 of Ordesky's book on Scala, I found that inner classes are path dependant. Among other features, that implies that they can only be instantiated within the outer class or giving an outer class instance.

The question arises: I would like to implement an static inner class in Scala but the author suggest that is not possible. I immediatelly thought of making the "inner class" (lets call it Inner) a member of Outer's companion object.

The accepted answer of this question seems to point towards that direction. But that drives to a problem: Inner's type ins't Outer#Inner, I could try something like:

object Outer {
    class Inner extends Outer#Inner { } 
}

This doesn't work however. Do you know a work arround for this? I have the hunch that it could be done with abstract types but I am not sure.

Note that making Inner an inner class of the companion objects is not exactly as having a non-path-dependant Inner class because of its type.

1

There are 1 answers

0
Alexey Romanov On BEST ANSWER

I immediatelly thought of making the "inner class" (lets call it Inner) a member of Outer's companion object.

Yes, that's the closest Scala equivalent.

But that drives to a problem: Inner's type ins't Outer#Inner

This isn't a problem, because Outer#Inner is equivalent to a non-static inner class of Outer in Java. I.e. it has a reference to an Outer object.

I would like to get a inner class which is not path dependant or, at least, to know if that is possible

If you want to create a non-companion inner class which can't be used path-dependently, it isn't possible. You are free to always write Outer#Inner instead of o.Inner in your code, of course.