Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compute property only once

Tags:

kotlin

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?

like image 286
Mibac Avatar asked Sep 05 '25 05:09

Mibac


1 Answers

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() }
}
like image 58
holi-java Avatar answered Sep 07 '25 22:09

holi-java