0

why there is no parentheses with outer in print statement and what's that mean?

    class outer() {
        var name = "mr X"
    
        class nestedclass {
            var description = "Inside the nested class"
            var id = 101
            fun foo() {
                println("id is $id")
    
            }
        }
    }
    
    fun main() {
        println(outer.nestedclass().description)  why there is no () with outer?
        outer.nestedclass().foo()
        var obj = outer.nestedclass()
        obj.foo()
        println(obj.description)
    }
Tenfour04
  • 83,111
  • 11
  • 94
  • 154
Haider
  • 21
  • 4

1 Answers1

1

There are no parens, because it's not creating an instance of outer.

If nestedclass were an inner class, then each instance would be associated with an instance of outer, so you'd need to construct the latter before the former.  (And you could do that by adding the parens, as outer().nestedclass().)

But it's only a nested class — defined within the lexical scope of outer, but not associated with an instance.  So outer.nestedclass is simply the class name, and you can call its constructor directly as outer.nestedclass().

So the line:

println(outer.nestedclass().description)

constructs an instance of outer.nestedclass, gets the value of its description property, and prints that out.

(If you know Java, there are two big differences to mention.  First, in Java inner classes are the default, and you need to specify static to make them nested; but in Kotlin, nested classes are the default, and there's an inner keyword.  And second, Kotlin doesn't have Java's new keyword to indicate a constructor call, so it can be harder to spot them.)

(Also, as Tenfour04 says, it's conventional to start class names with a capital letter, AKA PascalCase.  That makes them much easier to distinguish from method names and other identifiers — which are conventionally in camelCase.  This question is one situation in which the extra clarity would help.)

gidds
  • 16,558
  • 2
  • 19
  • 26
  • It’s especially hard to spot constructor calls when classes don’t follow the Pascal-case naming convention. – Tenfour04 Nov 17 '20 at 18:56
  • @Tenfour04 Indeed!  I've commented about that so many times…  Can we set up an FAQ or something with basic coding conventions, warnings about unnecessary use of Reflection, the difference between casting and converting, and the other things we keep saying? – gidds Nov 17 '20 at 19:01
  • Sometimes it's because people are just learning this language after using one that has different conventions. – Tenfour04 Nov 17 '20 at 19:06