Skip to content

Instantly share code, notes, and snippets.

@kassisdion
Created January 25, 2018 21:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kassisdion/a51598637cf16feeb81face622dd7f44 to your computer and use it in GitHub Desktop.
Save kassisdion/a51598637cf16feeb81face622dd7f44 to your computer and use it in GitHub Desktop.
public interface BaseRxValidator<T> extends Function<T, Boolean> {
}
public class StringValidator implements BaseRxValidator<String> {
public static final int EMPTY = 0;
public static final int TOO_SHORT = 1;
@Retention(RetentionPolicy.SOURCE)
@IntDef({EMPTY, TOO_SHORT})
public @interface Error {}
@Error
public int error;
@Override
@NonNull
public Boolean apply(@NonNull String target) throws Exception {
if (target.isEmpty()) {
error = EMPTY;
return false;
} else if (target.length() < 2) {
error = TOO_SHORT;
return false;
}
return true;
}
}
class ReusableValidator {
abstract class Validator<in T> {
data class Result(val isValid: Boolean, val error: Long?)
abstract fun isValid(target: T): Result
}
class StringValidator : Validator<String>() {
companion object {
const val EMPTY = 0L
const val TOO_SHORT = 1L
@Retention(AnnotationRetention.SOURCE)
@IntDef(EMPTY, TOO_SHORT)
annotation class Error
}
override fun isValid(target: String): Result {
return when {
target.isEmpty() -> Result(false, EMPTY)
target.length < 2 -> Result(false, TOO_SHORT)
else -> Result(true, null)
}
}
}
}
class NonReusableValidator {
abstract class Validator<out T>(val target: T) {
data class Result(val isValid: Boolean, val error: Long?)
abstract val isValid: Result
}
class StringValidator(target: String) : Validator<String>(target) {
companion object {
const val EMPTY = 0L
const val TOO_SHORT = 1L
@Retention(AnnotationRetention.SOURCE)
@IntDef(EMPTY, TOO_SHORT)
annotation class Error
}
override val isValid: Result
get() {
return when {
target.isEmpty() -> Result(false, EMPTY)
target.length < 2 -> Result(false, TOO_SHORT)
else -> Result(true, null)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment