Micha Roon
Micha Roon

Reputation: 4007

NullPointerException while all values are non null

in my class init a property is set to the value of a parameter. Neither the parameter nor its property is null but there is a null pointer exception

init {
    creationDate = owner.network.currentDate
}

you can try it online here

Exception in thread "main" java.lang.NullPointerException
    at Vault.<init>(Vault.kt:13)
    at NetworkProductionVault.<init>(Vault.kt:65)
    at Snc_tokenKt.main(snc-token.kt:13)

Upvotes: 0

Views: 132

Answers (1)

Yoni Gibbs
Yoni Gibbs

Reputation: 7018

I added this to init in Vault.kt in your example:

if (owner == null) println("owner is null")

And it is indeed null.

I think the reason is because you've declared this property (owner) as open, but you're referring to it when initializing the superclass. So it's going to be null at that point because the superclass will try to get the value from the subclass, but the subclass won't have been initialized yet. This is explained in a bit more detail here.

Upvotes: 3

Related Questions