Kotlin gives out different ways to declare properties in a class. How they are declared affects when they are evaluated.

Lets take this simple example:

class Test {

private fun returnSomething(str: String):String {

println("evaluating $str")

return str

}



val testGetEquals

get() = returnSomething("testGetEquals")

val testGetBrackets: String

get() { return returnSomething("testGetBrackets") }

}

After creating an instance of Test, calling the getter of testGetEquals will evaluate via returnSomething each time. The same is true with testGetBrackets .

I often write my simple val properties like so:

val testEquals = returnSomething("testEquals")

But this changes testEquals to be evaluated only once when the class is created. If this was an Android Activity or Fragment and the evaluation of the String relied on you have the Context this would result in a crash or an incorrect value.

So if I want to only evaluate the property once Kotlin has another trick.

val testLazy by lazy { returnSomething("testLazy") }

This is also evaluated only once. But it evaluated the first time it is called.

Please follow the link below to try this for yourself in the Kotlins playground

About Me

I am a Kotlin/Java Android developer Contractor. I am always interested to hear about your project and what I can do to help each other. www.wedgetech.co.uk