Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save AhmedMourad0/45b7fd43f014661795f4ff3833a47be0 to your computer and use it in GitHub Desktop.
Save AhmedMourad0/45b7fd43f014661795f4ff3833a47be0 to your computer and use it in GitHub Desktop.
Code snippets for the `value-based classes and error-handling` Medium article.
@NoCopy
data class Password private constructor(val value: String) {
companion object {
fun of(value: String): Either<List<Violation>, Password> {
val violations = buildList {
if (value.isTooShort()) { add(Violation.PasswordTooShort(MIN_LENGTH)) }
if (value.containsNoNumbers()) { add(Violation.PasswordContainsNoNumbers) }
}
return if (violations.isEmpty()) Password(value).right() else violations.left()
}
}
sealed class Violation {
data class PasswordTooShort(val minLength: Int) : Violation()
object PasswordContainsNoNumbers : Violation()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment