Skip to content

Instantly share code, notes, and snippets.

@luangs7
Last active August 15, 2018 15:31
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 luangs7/68de0edd14df64630d221881665a3d8c to your computer and use it in GitHub Desktop.
Save luangs7/68de0edd14df64630d221881665a3d8c to your computer and use it in GitHub Desktop.
An example of creating a Swift like guard let extension function in Kotlin with rule validation
inline infix fun EditText.guard(rule:Boolean,call: () -> Unit): String? {
if (this.text.isNotEmpty() && rule) return text
else {
call()
return null
}
}
fun String.isEmail(): Boolean {
val p = "^(\\w)+(\\.\\w+)*@(\\w)+((\\.\\w+)+)\$".toRegex()
return matches(p)
}
//example of usage
val phone = field.guard(field.isEmail()){
println("Your phone is incorrect!")
return null
}
println($phone)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment