Skip to content

Instantly share code, notes, and snippets.

@johnkil
Last active March 30, 2021 16:12
Show Gist options
  • Save johnkil/b0e605071e5157d56a5eae4700e39055 to your computer and use it in GitHub Desktop.
Save johnkil/b0e605071e5157d56a5eae4700e39055 to your computer and use it in GitHub Desktop.
interface Validator<in V, out E> {
fun validate(value: V): ValidationResult<E>
}
class CompositeValidator<in V, out E>(
private vararg val validators: Validator<V, E>
) : Validator<V, E> {
override fun validate(value: V): ValidationResult<E> {
for (validator in validators) {
val result = validator.validate(value)
if (result is Invalid) {
return result
}
}
return Valid
}
}
sealed class ValidationResult<out E> {
object Valid : ValidationResult<Nothing>()
data class Invalid<E>(val error: E) : ValidationResult<E>()
fun errorOrNull(): E? =
when (this) {
is Invalid -> error
Valid -> null
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment