Home > Blockchain >  When to put () on upper class and when not?
When to put () on upper class and when not?

Time:12-19

enter image description here

This is Kotlin but in other languages, I have this question.

When we put sub class in super class or when we call members in class, I see sometimes people put () on that parent class and sometimes not.

  • Outer.Nested().foo()
  • Outer().Nested().foo()

what makes some have () and some not?

CodePudding user response:

In the Kotlin docs, these are the key sentences:

A nested class marked as inner can access the members of its outer class. Inner classes carry a reference to an object of an outer class:

Without inner, the nested class is basically just a code organizational tool: the Nested class is its own, independent class. Other than the Outer.Nested notation (and things like functional visibility), the instances of the two classes are essentially unrelated.

But with inner, each Nested instance can see its Outer's instance members. To do that, it needs to know which instance of Outer. That means that each inner Nested instance needs to be created within the context of a specific Outer instance. That's what Outer() is doing. You could have also done:

val oObj = Outer()
val iObj = oObj.Inner() // "iObj" carries a reference to "oObj"
  • Related