Last active
March 30, 2021 16:12
-
-
Save johnkil/b0e605071e5157d56a5eae4700e39055 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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