We can now put to use what we learned about receiver and infix functions and create a DSL for validating objects. To keep it simple, we'll only be validatingInt
types.
First, we'll add the NumberValidator
interface. This is where all the different validators can represent their validation logic:
interface NumberValidator { fun isValueValid(value: Int): Boolean }
Then, we need a type that will keep all the validators and the validated object. We'll name it Validator
:
class Validator<T> private constructor(private val validatedObject: T) { internal val validators = mutableListOf<NumberValidator>() private lateinit var valueFactory: (T) -> Int }
To enforce type safety, the Validator
type is generic. It has a list of validators and also holds a function type called valueFactory
, which knows how to return a property that will be validated. Notice how the constructor is private. We don’t allow the validator type to be created from outside; instead, we use an...