How to have custom setter with check of the parame

2019-08-09 17:12发布

问题:

I am new to Kotlin and I can't wrap my head around a extremely basic problem:

I want to have a custom setter and to check if the parameter value is valid (and throw exception if not).

My code:

class Test {
    var presni: Int = 1
        set(value) {
            if (value < 0) {
                throw IllegalArgumentException("Negative value");
            }

            presni = value
        }
}

but it gives me warning at the presni = value line: Recursive property accessor

What is the idiom in Kotlin for checking the parameter in a setter for validity?

回答1:

You have to use the automatic backing field provided by Kotlin. You can access to it using the field identifier.

class Test {
    var presni: Int = 1
        set(value) {
            if (value < 0) {
                throw IllegalArgumentException("Negative value");
            }

            // Assign the value to the backing field.
            field = value
        }
}


回答2:

To validate a value before saving it in the backing field you can also use the Vetoable Delegate.

This is an example:

var presni: Int by Delegates.vetoable(1,{ _, _, newValue ->
        newValue >= 0
    })

The official documentation says:

If the callback returns true the value of the property is being set to the new value, and if the callback returns false the new value is discarded and the property remains its old value.



标签: kotlin