I really like the pattern og validated data types. In Kotlin I've seen it done like this
Copy code
@JvmInline
value class Email(val value: String) {
companion object {
private const val emailRegex = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+\$"
fun from(email: String): Either<FieldValidationFailure, Email> =
either {
ensure(email.matches(emailRegex.toRegex())) { InvalidEmail(email) }
Email(email)
}
}
}
However i really dislike having to .value to get the actual values out whenever I need them. Are there any other ways of doing this in kotlin?
a
Alejandro Serrano.Mena
10/03/2024, 7:52 AM
not really if you want to keep the type safety
d
David
10/03/2024, 1:55 PM
Also an addition, do prevent unwanted creations of
Email
it could be worth make it's constructor private:
Copy code
value class Email private constructor(val value: String) {
d
dave08
10/05/2024, 8:25 PM
You could inherit the Email class from CharSequence by value
j
J
10/07/2024, 7:19 AM
Could you elaborate on that Dave?
d
dave08
10/07/2024, 9:12 AM
Copy code
@JvmInline
value class Email(val value: String): CharSequence by value {
companion object {
private const val emailRegex = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+\$"
fun from(email: String): Either<FieldValidationFailure, Email> =
either {
ensure(email.matches(emailRegex.toRegex())) { InvalidEmail(email) }
Email(email)
}
}
}
dave08
10/07/2024, 9:13 AM
Then all the CharSequence functions are delegated to Email @J. But you'd maybe loose the gains of a value class (?)...