Reputation: 4605
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:
Can we reference the property option with obj.isX() or obj.isX? Are both equivalent?
Which of these two declarations is better, the fun or the val property? Which is recommended Kotlin style? To me they appear equivalent, so it's not obvious which to choose. The property uses "val" and not "var" so it's a read-only getter, the function is also a read-only getter. As shown, they also both override functions or properties. If they are equivalent, why are there two ways to do the same thing? If not equivalent, what is the difference?
Is this documented anywhere? Haven't found any.
Why does the Java to Kotlin converter seem to alternate between the two? I cannot tell why it chooses one or the other. Sometimes both are chosen.
Upvotes: 2
Views: 287
Reputation: 3890
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
boolean
and are named is*
- the programmer should choose the declaration that suits his design better.Upvotes: 3