Kotlin Class Computed Properties

lefebvre

Paul Lefebvre

Posted on September 27, 2019

Kotlin Class Computed Properties

Here's a quick tip that I didn't notice when implementing a Kotlin class. I wanted to have a computed property that would return a value of a backing class's property.

This seemed pretty straightforward so I wrote it like this (not the actual code, but you'll get the idea):

val Age: Int = person.Age()
Enter fullscreen mode Exit fullscreen mode

The problem here is that a property like this is not really a computed property, even though it may look like it since it's getting the value from a function call. Instead this property is initialized only once when its class is created and thus the function is only called once. So if your Age function returns a different value based on information that is provided later then it won't be correct.

Instead the solution is to create an actual computed property by using get like this:

val Age: Int
    get() = person.Age()
Enter fullscreen mode Exit fullscreen mode

This is a read-only computed property and the get() is called each time so you'll always have the correct value from the Age() function.

Learn more about Kotlin class properties here: https://kotlinlang.org/docs/reference/properties.html

💖 💪 🙅 🚩
lefebvre
Paul Lefebvre

Posted on September 27, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related