Pavel Lobodinský created GROOVY-11360:
-----------------------------------------
Summary: Issue a warning when accessing static fields that are
"shadowed" by get() methods
Key: GROOVY-11360
URL: https://issues.apache.org/jira/browse/GROOVY-11360
Project: Groovy
Issue Type: Improvement
Components: Compiler
Affects Versions: 4.0.21
Reporter: Pavel Lobodinský
h1. Introduction
When having a static field in a class that is retrieved by lambda, a {{get()}}
method is invoked instead. See the example code below, where {{DataClass#get}}
is called instead of returning the value of the {{STR}} field.
{code:groovy}
class StaticPropertyIssueTest {
static def STR = "test"
static void main(String[] args) {
def dataClass = new DataClass(value: "test")
dataClass.with {
assert value == STR
}
}
}
class DataClass {
String value
String get(String str) { "Hello" }
} {code}
In the https://issues.apache.org/jira/browse/GROOVY-11144 discussion, I learned
that this is an expected behaviour.
The main reason why I find this behaviour counter-intuitive is, that if the
{{DataClass}} comes from a library, I have no clue the {{DataClass#get}} method
exists. This problem always happens with AVRO-generated classes in particular,
where every class extending the {{}}
{code:java}
org.apache.avro.specific.SpecificRecordBase{code}
implements a
{code:java}
public Object get(String fieldName) { ... }{code}
method.
Actually, the {{get()}} method may even come from my own code, but I just don't
realise it will be called because I simply only see the {{STR}} static field in
my currently implemented class.
h1. Improvement proposal
Since this is the intended way Groovy is supposed to work, it would be amazing
if the compiler could issue a warning that the static field's retrieval is
shadowed by a getter method that will be called rather than returning the
static field's value.
In my eyes, this is something one simply does not expect. A compiler warning
together with advice, that we must qualify the field retrieval by {{this}}
keyword or by a class name, would help to understand the root cause of a
misbehaving code.
--
This message was sent by Atlassian Jira
(v8.20.10#820010)