- Learn Kotlin Programming(Second Edition)
- Stephen Samuel Stefan Bocutiu
- 171字
- 2021-06-24 14:13:37
Companion object extensions
Extension functions can also be added to companion objects. They would then be invoked on the companion object rather than on instances of the class.
One example of where this might be useful is when you are adding factory functions to a type. For example, we might wish to add a function to integers in order to return a different random value upon each invocation:
fun Int.Companion.random(): Int { val random = Random() return random.nextInt() }
Then, we can invoke the extension function as normal, without needing the Companion keyword:
val int = Int.random()
This isn't as useful as regular extension functions. This is because we can always create a new object and put the function in there or create a top-level function. But you may wish to associate a function with some other type's namespace. As in the preceding example, a random() function invoked on the Int type is more intuitive than the same function on a class with a name such as IntFactory or RandomInts.
- Vue.js 3.x快速入門
- Getting Started with Gulp(Second Edition)
- Oracle Database In-Memory(架構與實踐)
- Java 9 Programming Blueprints
- Full-Stack Vue.js 2 and Laravel 5
- SSM輕量級框架應用實戰
- Building a Quadcopter with Arduino
- Learning DHTMLX Suite UI
- Mastering Adobe Captivate 7
- Flink技術內幕:架構設計與實現原理
- Modernizing Legacy Applications in PHP
- Web前端開發最佳實踐
- Java程序設計實用教程(第2版)
- 邊做邊學深度強化學習:PyTorch程序設計實踐
- Lucene 4 Cookbook