- 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.
- Advanced Quantitative Finance with C++
- Beginning Java Data Structures and Algorithms
- Microsoft Dynamics 365 Extensions Cookbook
- Learning JavaScript Data Structures and Algorithms
- 數據結構與算法分析(C++語言版)
- 51單片機C語言開發教程
- Oracle GoldenGate 12c Implementer's Guide
- Python 3.7從入門到精通(視頻教學版)
- Go語言開發實戰(慕課版)
- C陷阱與缺陷
- Java7程序設計入門經典
- Android應用開發實戰(第2版)
- 深入實踐DDD:以DSL驅動復雜軟件開發
- Learning QGIS(Second Edition)
- 人件集:人性化的軟件開發