Attempt to invoke interface method 'java.lang.Object kotlin.Lazy.getValue()' on a null object reference
I'm not a pro but I'd like to tell you what I've found. Let's create a simple class to see how delegates in Kotlin work. Just in case, I'm using Kotlin 1.3.70
. Here is our simple class:
class Test {
val test by lazy { "test" }
}
In the Idea or Android Studio, you can check the bytecode. But it's pretty hard to read JVM bytecode at least for me :) Let's convert it to something looks like Java:
...
public final class Test {
@NotNull
private final Lazy test$delegate;
@NotNull
public final String getTest() {
Lazy var1 = this.test$delegate;
Object var3 = null;
boolean var4 = false;
return (String)var1.getValue();
}
public Test() {
this.test$delegate = LazyKt.lazy((Function0)null.INSTANCE);
}
}
...
As you see Kotlin creates a special field for lazy
delegate which initializes in the constructor. The problem is Gson uses UnsafeAllocator and doesn't call the constructor. You can read a bit more about it for example here. So when you deserialize your Article
object it contains null
instead of appropriate lazy
delegate. That's why you got a null pointer exception when trying to call this del