Say you have the following Java class:
public class MyClass
private String name = "";
public String getName()
Then you can do the following in Kotlin:
However, IntelliJ recognizes the prefix
get and will suggest you use property notation:
Furthermore, IntelliJ offers code completion for the latter option only
So far, this is great: name is a property and should be accessed like one, using the concise syntax.
This becomes a problem when there is a Java method with prefix
get that is actually not a property. Sometimes, the line between methods and properties may be blurry, but sometimes it is quite clear. E.g.,
javax.persistence.Query.getResultList() is clearly a method:
- It would be strange to think of a result as a “property” of a query.
- An invocation may returns a different instance each time.
- The method may hit the database.
query.resultList would actually be misleading and masquerading a potentially expensive method call. It is better to write
query.getResultList(), but IntelliJ will discourage you to do so.
The ideal solution to this problem would involve a new annotation
@NoProperty that gets added to all Java methods like
Query.getResultList(). Since this is not going to happen, I suggest that IntelliJ should allow you to configure
get-prefixed methods that are supposed to be called like methods. A default list could be community-curated. It is very unlikely that there will be versioning issues. Another option could be bytecode analysis to find out whether
get-prefixed methods ultimately only access fields (possibly via a chain of
get-prefixed methods). If so, they are properties, otherwise the are not.
For background information, you might want to check out the guide on properties vs. methods in .NET.
The Kotlin reference also has a small section on functions vs. properties, giving basically the same advice as the .NET 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 any Exceptions
- has a O(1) complexity
- is cheap to calculate (or caсhed on the first run)
- returns the same result over invocations