Limit permitted integer values for serialised class property with Kotlin

 To limit permitted integer values for a serialized class property in Kotlin, you can use custom accessors (getters and setters) and validation logic within your class. Here's an example of how to do this:


```kotlin

import kotlinx.serialization.Serializable


@Serializable

class YourSerializedClass {

    // Define a property for the integer value.

    private var _yourIntegerProperty: Int = 0


    // Define a getter for the property.

    var yourIntegerProperty: Int

        get() = _yourIntegerProperty

        set(value) {

            // Add validation logic to limit permitted values.

            if (value >= 0 && value <= 100) {

                _yourIntegerProperty = value

            } else {

                throw IllegalArgumentException("Value must be between 0 and 100.")

            }

        }

}


fun main() {

    val instance = YourSerializedClass()


    // Set the property with valid values.

    instance.yourIntegerProperty = 42


    // Try setting the property with an invalid value.

    try {

        instance.yourIntegerProperty = 150 // This will throw an exception.

    } catch (e: IllegalArgumentException) {

        println(e.message)

    }

}

```


In this example:


1. We define a private property `_yourIntegerProperty` to store the integer value.

2. We provide a custom getter and setter for the `yourIntegerProperty`. Inside the setter, we add validation logic to restrict the permitted values between 0 and 100.

3. When setting the property with an invalid value, it will throw an `IllegalArgumentException`.


This approach ensures that only permitted values are set for the `yourIntegerProperty` while maintaining serialization capability. However, be aware that this validation only works when setting the property directly. If you are deserializing data into this class, you may need to add additional validation during deserialization.

Comments

Popular posts from this blog

bad character U+002D '-' in my helm template

GitLab pipeline stopped working with invalid yaml error

How do I add a printer in OpenSUSE which is being shared by a CUPS print server?