DEV Community

Paul Lefebvre
Paul Lefebvre

Posted on • Edited on

3

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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay