Is there any difference in Kotlin between a private property with just a getter and a private function?

Viewed 48

I've seen the following Kotlin code, which to me seems just like a more verbose way to do what a function can do. Why would anyone choose to do:

private val foo: Rect
  get() = memberField

instead of doing this:

private fun foo(): Rect = memberField

It seems like the fun version is more straightforward to read, but maybe I'm missing something?

3 Answers

When I see the Kotlin byte code and decompile it, I see no difference between the two, so I'm mostly sure there is no difference between them. It might come down to readability, but you should be thinking in terms of state and behaviour. If you think any candidate should describe the state of the class, you should go for the getter, and if you think it should be describing a functionality or behaviour, you should go for functions.

private static final Rect getFoo() {
   return memberField;
}

private static final Rect foo() {
   return memberField;
}

Using a function instead of a property to simply return something is unconventional code in Kotlin. So, the downside of the function is that the code is a little less readable and easy to follow (more so at call sites than at the declaration site). Maybe not for you specifically if that’s your own style of writing code, but people might not like having to collaborate with you. :)

If the value is unchanging, you don’t need a custom getter. You can just write

private val foo: Rect = memberField

Though I’m not sure what the point of this property is if it just passes through the value of another property.

In practice you don’t frequently need to write custom getters and setters except when implementing interfaces that have properties.

I’m assuming memberField is actually a property. Fields in Kotlin are only accessible via field and it wouldn’t be possible to use it in your getter if you don’t provide an initial value for the property.

It's good to think of this from the user's perspective. Properties make sense when describing the state of an object, for example city.population rather then city.population().

This is not a hard rule, more of a heuristic.

Related