It isn’t a problem, just a proposal.
It isn’t about creating new types, but adding constraints that are natively checked when aliasing a type.
It is just to empower, fluidify and speed up basic and borings checks, in a concise and safe way.
It means, “when using the alias Email, it’s guaranteed that the String you are dealing with, matches the regex (or whatever) defined”. You’re right, it’s runtime validation.
But, maybe the “alias” way is not the one that matches my needs…
I know the syntax may be confusing (look like “constructors”), I would try to find something that suits better.
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.