Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Validation of uninitialized properties #49

Open
majster-kat opened this issue Aug 3, 2020 · 1 comment
Open

Validation of uninitialized properties #49

majster-kat opened this issue Aug 3, 2020 · 1 comment

Comments

@majster-kat
Copy link

Validation fails with UninitializedPropertyAccessException if I try to validate uninitialized lateinit variable.
For example:

class A {
    lateinit var v: String
}
validate(A()) {
    validate(A::v).isNotEmpty()
}

fails with exception kotlin.UninitializedPropertyAccessException: lateinit property v has not been initialized

I haven't found any solution in documentation for this situation (please correct me if I'm wrong). So here is my solution:

Create Uninitialized constraint and update validate method in Property to catch the exception.
Unitialized constraint is quite simple:

object Uninitialized : Constraint

Then new message should be added to messages.properties:

org.valiktor.constraints.Uninitialized.message=Must be initialized

And finally validate method can be updated like this:

fun validate(constraint: (T?) -> Constraint, isValid: (T?) -> Boolean): Property<T> {
    val value = try {
        this.property.get(this.obj)
    } catch(e: UninitializedPropertyAccessException) {
        this@Validator.constraintViolations += DefaultConstraintViolation(
                property = this.property.name,
                value = null,
                constraint = Uninitialized
        )
        return this
    }
    if (!isValid(value)) {
        this@Validator.constraintViolations += DefaultConstraintViolation(
            property = this.property.name,
            value = value,
            constraint = constraint(value)
        )
    }
    return this
}

Similarly coValidate should be updated as well.

@majster-kat
Copy link
Author

If you like the idea, then I can create pull request.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

1 participant