Search code examples
androidkotlinhashcode

Kotlin 1.5.2 data class hashcode( ) generated implementation will result in nullPointerExeption


First, while Gson converting json string to Kt data class, Gson maybe use 'UnSafe' create data class, and assign 'null' for a NoNull field. And when this object's hashcode() being invoked, a nullPointerException is thrown.

Cause the generated bytecode by kt compiler doesn't check every field, has anybody met this issue yet?

Below shows the generated hashcode by 1.5.20 kt-compiler.

 public int hashCode() {
    result = this.eventId.hashCode();
    return result * 31 + this.voteId.hashCode();
  }

Solution

  • This is an odd thing to take issue with! To understand the generated hashCode() method, take a look at the pseudocode explanation at: https://discuss.kotlinlang.org/t/how-does-kotlin-implement-equals-and-hashcode/940/2

    The problem you're encountering is that when Gson creates and object with a null field, you've already promised the compiler that it will not be null so it doesn't try to catch this case in hashCode().