1.语法如下:
fun main(args: Array<String>) {
}
class Person {
//非静态
var age = 20
//伴生对象
companion object {
//静态
var name = "张三"
}
}
2.实现和java一样的单例
fun main(args: Array<String>) {
println(Person.instance.age)
}
class Person private constructor() {
//非静态
var age = 20
companion object {
//静态
var name = "张三"
val instance by lazy {
Person()
}
}
}
- 惰性加载,只会加载一次,线程安全
网友评论