Posts

Showing posts with the label Kotlin

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 prop