Implicit validation calls
So basically you want a validation method to be called implicitly when that type is assigned or passed as an argument? For example:
typealias PinCode = Int(minLength = 4, maxLength = 8)
val myPin = readInputFromUser() // An exception is thrown here if user typed too long of a pin.
This kind of exception throwing behavior would be similar to the behavior if the user inputs a string instead of a valid integer.
Current validation options for primatives
Currently, this functionality must be done explicitly. For example:
val myPin = validatePin(readInputFromUser()) // Using a validator function.
val myPin = readInputFromUser().validPin // Using a validator function.
val myPin = readPinFromUser() // Using specific functions for each use.
The proposal could do additional validation checks while the current setup would be best used at the edges of the input.
Another solution to get implicit validation on assignment (without using a custom setter) is property delegation–using a delegate where one could provide a validator lambda.
I get the idea of having a guaranteed valid email, but that is exactly what classes are for. If it’s a Pin Code then it’s not an Int. If it’s an Email then it’s not a String.
See the Liskov Substitution Principle
Inline classes may be a good option for this use case if you really want the state to be represented as a primitive. Classes would work just fine though–and still provide the same guarantee that emails and pins are valid.