Skip to content

Instantly share code, notes, and snippets.

@ngsw-taro
Created October 31, 2018 07:20
Show Gist options
  • Save ngsw-taro/5d4d37cf5b1bb4f947d909eafb69f758 to your computer and use it in GitHub Desktop.
Save ngsw-taro/5d4d37cf5b1bb4f947d909eafb69f758 to your computer and use it in GitHub Desktop.
Yavi Kotlin Extensions
data class UserPostBody(val age: Int?,
val name: String?)
@JvmName("intConstraint")
fun <T> ValidatorBuilder<T>.constraint(prop: KProperty1<T, Int?>, block: IntegerConstraint<T>.() -> Unit): ValidatorBuilder<T> {
return this.constraint(prop, prop.name) { it.apply(block) }
}
@JvmName("charSequenceConstraint")
fun <T, E : CharSequence?> ValidatorBuilder<T>.constraint(prop: KProperty1<T, E>, block: CharSequenceConstraint<T, E>.() -> Unit): ValidatorBuilder<T> {
return this.constraint(prop, prop.name) { it.apply(block) }
}
fun main() {
// before
/*
val validator = Validator.builder<UserPostBody>()
.constraint(UserPostBody::age, "age") { it.notNull() }
.constraint(UserPostBody::name, "name") { it.notBlank().lessThanOrEqual(20) }
.build()
*/
// after
val validator = Validator.builder<UserPostBody>()
.constraint(UserPostBody::age) { notNull() }
.constraint(UserPostBody::name) { notBlank().lessThanOrEqual(20) }
.build()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment