3

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.

Community
  • 1
  • 1
  • I assume you're not just worried about the name looking nice? What is the mechanical consequence/behaviour that you are missing, and want to emulate with you `Outer#Inner` attempt? – Andrzej Doyle Nov 18 '14 at 10:42
  • @AndrzejDoyle No, I am not just worried about the name, that could be solved with the answer I linked. I would like to get a inner class which is not path dependant or, at least, to know if that is possible. – Pablo Francisco Pérez Hidalgo Nov 18 '14 at 10:50

1 Answers1

1

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.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487