Sean F
Sean F

Reputation: 4605

Ambiguity between getters and properties in Kotlin, best practices?

I am using Intellij's Java to Kotlin converter.

When converting a function like this (in this example it is an overriding function but this also applies to non-overriding):

@Override
public boolean isX() {
    // code
}

it sometimes becomes

override val isX: Boolean
    get() {
    //code
    }

and other times it becomes

override fun isX(): Boolean {
   // code
}

Sometimes I get both at the same time and then the bytecode compiler complains I have two functions with the same JVM signature: isX()Z

It seems as though both options compile to isX() with the Kotlin bytecode compiler and are accessible with function calls isX()

So, this leaves me wondering several things:

Upvotes: 2

Views: 287

Answers (1)

ardenit
ardenit

Reputation: 3890

  1. Property getter is called only by obj.isX, function is called only by obj.isX()

2, 3. From official Kotlin coding conventions guide:

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 caсhed on the first run)

  • returns the same result over invocations if the object state hasn't changed

  1. Converter isn't perfect, the code it generates is meant to be refactored afterwards by the programmer. Both function and property declarations are suitable for Java methods that return boolean and are named is* - the programmer should choose the declaration that suits his design better.

Upvotes: 3

Related Questions