Search code examples
libgdxkotlin

Kotlin custom setter


I'm trying to make a custom property setter for libGDX's sprite.

var sprite : Sprite? = null
    get() = sprite
    set(s : String) { sprite = Sprite(Texture(s)) }

But it's saying that s must be of type Sprite, is it possible to do what i'm trying to do?


Solution

  • First of all you should be using field instead of sprite inside your custom getter/setter. Otherwise recursive calls will be the result.

    What you're trying to do does not work, as the compiler tells you. You need to overload the setter and add it as a normal method to your class like this:

    setSprite(s : String) { sprite = Sprite(Texture(s)) }