0

When I debug, I see that the inner class here gets a reference to its outer class, even though it's not using any values from the outer class. The only reason the inner class is an inner class is so it can reference the types of the outer class.

trait CorrectingParserWriter extends OptimizingParserWriter with EditorParserWriter {
  ...
  final class SRCons[+Result](val head: LazyParseResult[Result], _tail: => SortedParseResults[Result]) extends SortedParseResults[Result] {
    ...
  }
  ...
}

I added final in an attempt to remove the reference to outer, but with no success.

To reduce memory consumption, I don't want the small object SRCons to have a reference to its outer class. However, de-nesting this inner class introduces many type parameters, which makes the code a mess.

KeyboardDrummer
  • 577
  • 5
  • 21
  • 2
    It may relate to the fact that there is no single type `SRCons` but rather there is a different type `SRCons` for each instance of `CorrectingParserWriter`. So this outer reference may be required when checking the actual type of an instance of `SRCons` – Tim Apr 28 '19 at 08:14
  • That makes sense. However, I'm only comparing this type within the outer class, so I don't need to check equality on the outer class type. I've also tried making the inner class protected, but that didn't resolve the issue. – KeyboardDrummer Apr 28 '19 at 11:19
  • The compiler has to consider every possible usage of the class, not just current usage. In this case (even with `protected`) it is possible that some code might want to check the type of an `SRCons` object. And there is no guarantee that the compiler would remove this reference even if it theoretically could. – Tim Apr 29 '19 at 07:02
  • From type checker perspective this is a path-dependent type. From JVM perspective all inner classes (that are not `static`) keeps reference to an outer class, and you can always refer the instance of the outer class which created the instance of the inner class. – Mateusz Kubuszok Apr 29 '19 at 10:25
  • If you want it to not be a path-dependent type and for JVM to treat it as a static inner class put it inside a companion object. – Mateusz Kubuszok Apr 29 '19 at 10:28

0 Answers0