Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cache property read from database

Tags:

kotlin

Currently I'm starting to learn Kotlin. I have a property like this:

var startTime: Int
    get() = {
        // read value from database
    }
    set(value) {
        // save value to database
    }

Here I always read and write the value every time I use the getter and setter.

Can this property be evaluated lazy? I want to read the value once the first time I use the getter and cache it for following calls. I know that values can be lazy but I found nothing about variables. What is the correct way in Kotlin to cache this property?

like image 952
Cilenco Avatar asked Nov 15 '25 19:11

Cilenco


1 Answers

Kotlin offers lazy properties (https://kotlinlang.org/docs/reference/delegated-properties.html#lazy) that are computed on first access and cached.

val lazyValue: String by lazy {
  println("computed!")
  "Hello"
}

fun main(args: Array<String>) {
  println(lazyValue)
  println(lazyValue)
}

Will produce

computed!
Hello
Hello
like image 92
Strelok Avatar answered Nov 18 '25 08:11

Strelok



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!