1

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();
  }
xiaobin yáng
  • 146
  • 1
  • 11
  • 1
    Does this answer your question? [Why Kotlin data classes can have nulls in non-nullable fields with Gson?](https://stackoverflow.com/questions/52837665/why-kotlin-data-classes-can-have-nulls-in-non-nullable-fields-with-gson) – a_local_nobody Aug 19 '21 at 08:42
  • 1
    @a_local_nobody No, I know why null fields happed, I'm thinking kotlin data class hashcode implementation is somewhat weird. – xiaobin yáng Aug 19 '21 at 09:18
  • then you should make your question clearer to show specifically what you're asking, at the moment i don't understand what you're asking – a_local_nobody Aug 19 '21 at 09:19

1 Answers1

1

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().

Martin
  • 770
  • 6
  • 22