meow
meow

Reputation: 33

Kotlin Ternary conditional operator to typical if-else

Can someone turn this to if-else statements in Kotlin so that I can get an understanding of the code?

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!";

Upvotes: 0

Views: 2114

Answers (3)

Tenfour04
Tenfour04

Reputation: 93581

@ArtyomSkrobov's answer is a literal interpretation of that code.

I just wanted to add, since that original logic is very confusing: It can be rearranged in a when statement and use Kotlin standard library functions/classes to be a lot easier to understand:

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 -> ""
}

Upvotes: 4

samuele794
samuele794

Reputation: 86

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!"

Upvotes: 1

Artyom Skrobov
Artyom Skrobov

Reputation: 311

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!"

Upvotes: 2

Related Questions