I really like the pattern og validated data types....
# arrow
j
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
not really if you want to keep the type safety
d
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
You could inherit the Email class from CharSequence by value
j
Could you elaborate on that Dave?
d
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)
            }
    }
}
Then all the CharSequence functions are delegated to Email @J. But you'd maybe loose the gains of a value class (?)...