- Kotlin Programming By Example
- Iyanu Adelekan
- 128字
- 2021-08-27 20:00:13
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
}
推薦閱讀
- HTML5 Mobile Development Cookbook
- Windows Presentation Foundation Development Cookbook
- Building Cross-Platform Desktop Applications with Electron
- 從學(xué)徒到高手:汽車(chē)電路識(shí)圖、故障檢測(cè)與維修技能全圖解
- concrete5 Cookbook
- C語(yǔ)言開(kāi)發(fā)基礎(chǔ)教程(Dev-C++)(第2版)
- 編程與類(lèi)型系統(tǒng)
- Developing SSRS Reports for Dynamics AX
- 編程可以很簡(jiǎn)單
- C語(yǔ)言程序設(shè)計(jì)實(shí)訓(xùn)教程與水平考試指導(dǎo)
- GitHub入門(mén)與實(shí)踐
- Modernizing Legacy Applications in PHP
- 大數(shù)據(jù)時(shí)代的企業(yè)升級(jí)之道(全3冊(cè))
- Drupal 8 Development:Beginner's Guide(Second Edition)
- 軟件測(cè)試技術(shù)