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)
}
There are no parens, because it's not creating an instance of
outer.If
nestedclasswere an inner class, then each instance would be associated with an instance ofouter, so you'd need to construct the latter before the former. (And you could do that by adding the parens, asouter().nestedclass().)But it's only a nested class — defined within the lexical scope of
outer, but not associated with an instance. Soouter.nestedclassis simply the class name, and you can call its constructor directly asouter.nestedclass().So the line:
constructs an instance of
outer.nestedclass, gets the value of itsdescriptionproperty, 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
staticto make them nested; but in Kotlin, nested classes are the default, and there's aninnerkeyword. And second, Kotlin doesn't have Java'snewkeyword 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.)