You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@avro.apache.org by "benoitcanton (via GitHub)" <gi...@apache.org> on 2025/11/12 20:40:47 UTC

Re: [PR] AVRO-3527: Generated equals() and hashCode() for SpecificRecords [avro]

benoitcanton commented on PR #1708:
URL: https://github.com/apache/avro/pull/1708#issuecomment-3523836333

   Hi @steven-aerts @RyanSkraba 
   
   This PR introduced a bug in the Avro tools 1.12.1 when a schema includes a field with name `result`. 
   
   In the following example, the schema contains two fields:
   - A field `result` of type `["null", "string"]` 
   - A field `anotherField` of type` enum
   
   The `hashCode` method generated based on the `record.vm` template will be as follow:
   
   ```java
     @Override
     public int hashCode() {
       int result = 1;
       result = 31 * result + (eventHeader == null ? 0 : eventHeader.hashCode());
       result = 31 * result + (result == null ? 0 : result.hashCode());
       result = 31 * result + (anotherField == null ? 0 : ((java.lang.Enum) anotherField).ordinal());
       return result;
     }
   ```
   
   Now since the schema has a field `result` of type `["null", "string"]` and the generated `hashCode` method declares a `result` of type `int`. The `result.hashCode()` will fail since the local `result` takes precedence.
   
   Trying to compile a project using the generated java class throws:
   
   ```
   Compiling with JDK Java compiler API.
   ..../MyEvent.java:1744: error: bad operand types for binary operator '=='
       result = 31 * result + (result == null ? 0 : result.hashCode());
                                      ^
     first type:  int
     second type: <null>
   ..../MyEvent.java:1744: error: int cannot be dereferenced
       result = 31 * result + (result == null ? 0 : result.hashCode());
                                                          ^
   2 errors
   > Task :compileJava FAILED
   ```
   
   For the sake of validating my findings, I have updated my schema and renamed my field `result` to `res` and sure enough that "fixed" the issue. Obviously, this is not a solution.
   
   One workaround would be to use custom Velocity templates, to rename `int result = 1` to `int result2 = 1` (just an example) but that is unpractical to maintain.
   
   @steven-aerts @RyanSkraba  It would be great if we could rename the `result` in the `record.vm` template to be something less common.
   
   If this Github thread is not the right place to report this bug, please let me know where to report it. Thanks!


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org