vyi
vyi

Reputation: 1092

Instantiating an object within the object declaration in kotlin

While browsing through kotlin documentation at object expressions and declarations I came across this snippet

class MyClass {
    companion object Factory {
        fun create(): MyClass = MyClass()
    }
}

val instance = MyClass.create()

In line 3, the create function instantiates an object MyClass()

In last line however, to call the create we already need MyClass object (don't we?).

My question is: At what point does the MyClass comes into existence?

Upvotes: 1

Views: 315

Answers (2)

hotkey
hotkey

Reputation: 148179

In last line however, to call the create we already need MyClass object (don't we?).

No, the last line calls .create() on the companion object of MyClass. The companion object is an instance of a separate class (it is not MyClass) and is initialized before the class is first used, so you don't need an instance of MyClass to call .create().

Note that, syntactically, .create() is called on the MyClass class name, not on an ordinary exppression like MyClass() constructor call or a myClass variable.

Upvotes: 2

s1m0nw1
s1m0nw1

Reputation: 82117

The invocation val instance = MyClass.create() is independent of an instance of MyClass, you simply use the type as a qualifier for the method (it's like static methods in Java). Note that you can also write MyClass.Factory.create(), the companion's name is redundant when calling it from Kotlin though.

Upvotes: 2

Related Questions