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

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
}
主站蜘蛛池模板: 宁陕县| 孝感市| 江山市| 镇安县| 南投市| 共和县| 宜宾县| 东兰县| 丹阳市| 多伦县| 休宁县| 宝山区| 彰武县| 绥德县| 兴山县| 漳平市| 军事| 桑日县| 林芝县| 佛山市| 汪清县| 桐梓县| 霞浦县| 定安县| 武邑县| 驻马店市| 印江| 江永县| 兴国县| 广西| 阜南县| 景洪市| 青岛市| 得荣县| 怀远县| 唐海县| 明水县| 大冶市| 南漳县| 永德县| 瑞丽市|