Kotlin 三元条件运算符到典型的 if-else
Kotlin Ternary conditional operator to typical if-else
有人可以将其转换为 Kotlin 中的 if-else 语句,以便我可以理解代码吗?
return email != null
? email.isEmpty
? "Please enter your email!"
: RegExp("^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+.[a-z]")
.hasMatch(email)
? ""
: "Please enter a valid email!"
: "Please enter your email!";
return if (email != null) {
if (email.isEmpty) "Please enter your email!"
else if (RegExp("^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+.[a-z]").hasMatch(email)) ""
else "Please enter a valid email!"
} else "Please enter your email!"
return if (email != null){
when {
email.isEmpty() -> "Please enter your email!"
RegExp("^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+.[a-z]"). hasMatch(email) -> ""
else -> "Please enter a valid email!"
}
} else "Please enter a valid email!"
@ArtyomSkrobov 的回答是对该代码的字面解释。
我只是想补充一下,因为原来的逻辑很混乱:可以在 when 语句中重新排列并使用 Kotlin 标准库 functions/classes 更容易理解:
return when {
email.isNullOrEmpty() -> "Please enter your email!"
!email.matches(Regex("^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+.[a-z]")) -> "Please enter a valid email!"
else -> ""
}
有人可以将其转换为 Kotlin 中的 if-else 语句,以便我可以理解代码吗?
return email != null
? email.isEmpty
? "Please enter your email!"
: RegExp("^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+.[a-z]")
.hasMatch(email)
? ""
: "Please enter a valid email!"
: "Please enter your email!";
return if (email != null) {
if (email.isEmpty) "Please enter your email!"
else if (RegExp("^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+.[a-z]").hasMatch(email)) ""
else "Please enter a valid email!"
} else "Please enter your email!"
return if (email != null){
when {
email.isEmpty() -> "Please enter your email!"
RegExp("^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+.[a-z]"). hasMatch(email) -> ""
else -> "Please enter a valid email!"
}
} else "Please enter a valid email!"
@ArtyomSkrobov 的回答是对该代码的字面解释。
我只是想补充一下,因为原来的逻辑很混乱:可以在 when 语句中重新排列并使用 Kotlin 标准库 functions/classes 更容易理解:
return when {
email.isNullOrEmpty() -> "Please enter your email!"
!email.matches(Regex("^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+.[a-z]")) -> "Please enter a valid email!"
else -> ""
}