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 ...

Get Kotlin Programming By Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.