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

Companion objects

Companion objects are declared within a class by utilizing the companion and object keywords. You can use functions that are static within a companion object:

class Printer {
companion object DocumentPrinter {
fun printDocument() = println("Document printing successful.")
}
}

fun main(args: Array<String>) {
Printer.printDocument() // printDocument() invoked via companion object
Printer.Companion.printDocument() // also invokes printDocument() via
// a companion object
}

Sometimes, you may want to give an identifier to a companion object. This can be done by placing the name after the object keyword. Consider the following example:

class Printer {
companion object DocumentPrinter { // Companion object identified by DocumentPrinter
fun printDocument() = println("Document printing successful.")
}
}

fun main(args: Array<String>) {
Printer.DocumentPrinter.printDocument() // printDocument() invoked via
// a named companion object
}
主站蜘蛛池模板: 广汉市| 崇左市| 子洲县| 宁城县| 太湖县| 牡丹江市| 开原市| 丰宁| 烟台市| 建湖县| 洞口县| 三门县| 巴中市| 孟州市| 建水县| 西林县| 米林县| 珲春市| 涪陵区| 临猗县| 长兴县| 舒城县| 南乐县| 金山区| 九龙城区| 临朐县| 屏东县| 台州市| 冀州市| 洪雅县| 伊金霍洛旗| 巴林右旗| 时尚| 新民市| 卢氏县| 龙口市| 合肥市| 丹江口市| 屏南县| 双柏县| 凉城县|