Kotlin Programming By Example
上QQ阅读APP看书,第一时间看更新

Creating objects

Declaring an instance of a class—or an object—is similar to declaring a variable. We can create an instance of the HelloPrinter class, as shown in the following code:

val printer = HelloPrinter()

The preceding printer is an instance of the HelloPrinter class. The opening and closing brackets after the HelloPrinter class name are used to invoke the primary constructor of the HelloPrinter class. A constructor is similar to a function. A constructor is a special function that initializes an object of a type.

The function declared within the HelloPrinter class can be invoked directly by the printer object at any point in time:

printer.printHello() // Prints hello

Occasionally, you may require a function to be directly invokable with the class without needing to create an object. This can be done with the use of a companion object.