Given the following code
class A
class B {
val property: A
get() = A()
}
fun main(args: Array<String>) {
val b = B()
println(b.property)
println(b.property)
}
It returns a new A
instance every time B.property
. Is there an easy way to make it return the same instance every time?
You can use delegated properties lazy simply, for example:
class B {
val property by lazy(::A)
}
You can also use a lambda expression instead like this:
class B {
val property by lazy { A() }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With