Shunan
Shunan

Reputation: 3254

How to access variables in kotlin without invoking its setter and getter

I am working on a library where any change in argument refreshes the view. In refresh() function, I am setting some arguments' values to default values.

var viewAlpha= 255
        set(value) {
            field = value
            refresh()
        }

fun refresh() {
    viewAlpha = 255
    invalidate()
}

This is causing StackOverflowError due to obvious reasons.

Caused by: java.lang.StackOverflowError: stack size 8MB

Is it possible to access variables in kotlin without invoking its setter when we are accessing it in the same class. Similar to what we do in java.

Upvotes: 2

Views: 461

Answers (1)

TSB99X
TSB99X

Reputation: 3394

One way would be to provide you good ol' backing field to get out of setter-refres cycle:

private var _viewAlpha = 255

var viewAlpha
        get() {
            return _viewAlpha
        }
        set(value) {
            _viewAlpha = value
            refresh()
        }

fun refresh() {
    _viewAlpha = 255
    invalidate()
}

If you want to simplify your logic for multiple fields you can abstract this implementation into separate class and use callback call with direct setter that will work without refresh invocation. Like this:

class Field(val onSetCb: (Field) -> Unit) {

    private var viewAlpha = 255

    fun get() {
        return viewAlpha
    }

    fun set(value: Int) {
        setDirect(value)
        onSetCb(this)
    }

    fun setDirect(value: Int) {
        viewAlpha = value;
    }
}

// Elsewhere...

fun refresh(field: Field) {
    field.setDirect(255)
    invalidate()
}

val f = Field(::refresh)
f.set(255)

Upvotes: 5

Related Questions