因为有by lazy,所以kotlin写懒汉单例特别简单:
class Factory {
private constructor(){
println("factory 创建")
}
companion object{
val factory:Factory by lazy {
Factory()
}
}
}
fun main() {
println("start")
Factory.factory//如果这行代码不调用,factory 创建 就不会输出
}