Function vs immutable property

I frequently come across the situation where I want to derive an object from another one and have the choice to write an extension function or an extension property like so:

fun MyClass.foo(): MyOtherClass = ...
val MyClass.foo: MyOtherClass get() = ...

The difference on the call site is clear

val a: MyClass = ...
a.foo()
a.foo

I have a rough understanding that it is a question about action vs state, but in many situation it is not so clear and I can’t keep myself from getting lost in thinking about it, which drives me crazy a bit.

So, what are you strategies/rules/guidelines here? Or maybe you just don’t care?

2 Likes

From the kotlin documentation:

Functions vs properties

In some cases functions with no arguments might be interchangeable with read-only properties. Although the semantics are similar, there are some stylistic conventions on when to prefer one to another.

Prefer a property over a function when the underlying algorithm:

  • does not throw
  • is cheap to calculate (or cached on the first run)
  • returns the same result over invocations if the object state hasn’t changed
7 Likes