在Swift等其他語言中,可能會創建一個添加新構造函數的函數擴展。是否可以在Kotlin中創建擴展構造函數?
事情是這樣的:
// base class
class Whatever() {
...
}
// constructor method extension
fun Whatever.constructor(potato: String) {
setPotato(potato)
}
fun main(args: Array<String>) {
println(Whatever("holi"))
}
是否有任何手段在科特林做到這一點?
這不是模仿構造函數,它是工廠模式:) –
你是對的,但這有區別,你不需要調用Factory.foo(123)。糖代碼無論如何 – Aracem
@WilliMentzel它爲客戶端模仿一個構造函數:他們把它和構造函數一樣調用,不需要知道它是哪個。 –