[SOLVED] Kotlin lazy property in data class results in NullPointerException – Stack Overflow

Issue

This Content is from Stack Overflow. Question asked by metrik

I have a Kotlin interface that looks like this:

interface IGeneralData {
    val id: Int
    val name: String
}

and a data class that implements the interface which is created by either GSON or Jetpack Room:

@Entity
data class MyData(
    @PrimaryKey override val id: Int,
    override val name: String
) : IGeneralData {
    @delegate:Ignore
    val last: String by lazy {
        name.substring(name.lastIndexOf('.') + 1)
    }
}

Unfortunately, I get a NullPointerException I don’t understand when accessing the last property:

java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object kotlin.Lazy.getValue()' on a null object reference

When I look at the object in the debugger, at the time of accessing ‘last’ both the id field and the name field are populated. So where das this NPE come from?

Thank you!



Solution

This is just a guess, but I think Ignore fixes the issue for Room, but for GSON you need to use Transient. So you need both annotations:

@Entity
data class MyData(
    @PrimaryKey override val id: Int,
    override val name: String
) : IGeneralData {
    @delegate:Ignore 
    @delegate:Transient
    val last: String by lazy {
        name.substring(name.lastIndexOf('.') + 1)
    }
}


This Question was asked in StackOverflow by metrik and Answered by Tenfour04 It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?