很多時(shí)候我們要判斷EditText輸入的數(shù)據(jù)是否為空吟榴,在Java中需要以下代碼:
String mobile = etMobile.getText().toString();
if (TextUtils.isEmpty(mobile)) {
showError("手機(jī)號(hào)不能為空");
return;
}
String password = etPassword.getText().toString();
if (TextUtils.isEmpty(password)) {
showError("密碼不能為空");
return;
}
...
現(xiàn)在我們來(lái)看看同樣的事情用Kotlin怎么優(yōu)雅地實(shí)現(xiàn):
// 編寫(xiě)一個(gè)擴(kuò)展方法
fun TextView.checkBlank(message: String): String? {
val text = this.text.toString()
if (text.isBlank()) {
showError(message)
return null
}
return text
}
// 優(yōu)雅地判空
val mobile = etMobile.checkBlank("手機(jī)號(hào)不能為空") ?: return
val password = etPassword.checkBlank("密碼不能為空") ?: return