- Hands-On Design Patterns with Kotlin
- Alexey Soshin
- 143字
- 2021-06-25 20:49:28
Static Factory Method in Kotlin
We've already discussed the object keyword earlier in the Singleton section. Now we'll see another use of it is a companion object.
In Java, Static Factory Methods are declared static. But in Kotlin, there's no such keyword. Instead, methods that don't belong to an instance of a class can be declared inside a companion object:
class NumberMaster {
companion object {
fun valueOf(hopefullyNumber: String) : Long {
return hopefullyNumber.toLong()
}
}
}
Companion objects may have a name: companion object Parser, for example. But this is only for clarity of what the goal of this object is.
Calling a companion object doesn't require instantiating a class:
println(NumberMaster.valueOf("123")) // Prints 123
Moreover, calling it on an instance of a class simply won't work, unlike Java:
println(NumberMaster().valueOf("123")) // Won't compile
The class may have only one companion object.
推薦閱讀
- 計(jì)算機(jī)網(wǎng)絡(luò)
- Docker and Kubernetes for Java Developers
- C語(yǔ)言程序設(shè)計(jì)習(xí)題解析與上機(jī)指導(dǎo)(第4版)
- C# 從入門到項(xiàng)目實(shí)踐(超值版)
- JavaFX Essentials
- 基于Java技術(shù)的Web應(yīng)用開發(fā)
- Python編程完全入門教程
- Visual C++串口通信技術(shù)詳解(第2版)
- Mastering Yii
- Python數(shù)據(jù)結(jié)構(gòu)與算法(視頻教學(xué)版)
- Mastering JavaScript High Performance
- Clojure Reactive Programming
- ASP.NET開發(fā)與應(yīng)用教程
- jQuery炫酷應(yīng)用實(shí)例集錦
- 區(qū)塊鏈國(guó)產(chǎn)化實(shí)踐指南:基于Fabric 2.0