Search code examples
kotlinif-statementternary

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

Solution

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