官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 哈尔滨市| 原平市| 金坛市| 河北省| 呼玛县| 商城县| 白河县| 二连浩特市| 丹巴县| 永福县| 永仁县| 雅安市| 永川市| 揭阳市| 化州市| 邓州市| 岳西县| 含山县| 四川省| 内乡县| 东乡| 大埔区| 钟山县| 南江县| 峡江县| 鹿泉市| 昆明市| 东阳市| 彰化县| 三门县| 林周县| 辽阳县| 兰州市| 左云县| 亳州市| 南漳县| 镇巴县| 池州市| 五家渠市| 西丰县| 磐安县|