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?
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
}
}
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.