NPE on constructor when instantiating derived class


#1

I have the following code:

public class CurrentPlayer(override val game: PewGame, spriteSheet: String) : Player(game, spriteSheet)

The hierarchy is as follows: CurrentPlayer -> class Player -> trait MovingEntity -> trait Entity. The trait 'Entity' has a field 'val game: PewGame'. The constructor for Player looks like this:

public open class Player(override val game: PewGame, spriteSheet: String) : MovingEntity, InputAdapter()

In the constructor of Player, if you can call it that in kotlin, I have this:

this.sprite = CharacterSpriteSheet(Utilities.createTextureFromFile(spriteSheet), this.game.getSpriteBatch(), 0.25f)

Problem is, 'this.game' is null, therefore 'this.game.getSpriteBatch()' throws a NPE. I can't explain this in a better way, so any help is appreciated. To be more precise, after using a debugger: I can see both game and this in the Player class. game is not null, but this.game is null for some inexplicable reason. Thanks for helping!

EDIT: I forgot to mention that the issue is only present when I instantiate CurrentPlayer, and doesn’t happen when I instantiate Player.
EDIT #2: The full code, if needed, is here:

http://pastebin.com/ps20bbKh

http://pastebin.com/wvAGGDrR

http://pastebin.com/9Di8Nxza

http://pastebin.com/KxYnt0nW

Thanks.

EDIT #3:
Alright, I managed to get it to work. Somehow, in the constructor for CurrentPlayer:

public class CurrentPlayer(val agame: PewGame, …) : Player(agame, …)


Basically, for some reason I can’t use an overriden value/property/field/whatever to initialise a super class constructor. I’m not sure if this is a bug or intentional behaviour, and I’d like to find out so I’ll leave this unanswered for now.


#2

Answered on StackOverflow:

The problem is that you store the same data in two fields: you override game in Player and then again in CurrentPlayer, which makes the same data stored twice. Incidentally, it makes the getter for the gameproperty access an uninitialized field in CurrentPlayer instead of an initialized one in Player.

To fix this problem, just remove override val from CurrentPlayer declaration:

public class CurrentPlayer(game: PewGame, spriteSheet: String) : Player(game, spriteSheet)