stringkotlincase-whenisnullorempty

How to use checks like isNullOrEmpty in Kotlin when expressions


Like many other programming languages, Kotlin provides checks like isNullOrEmpty, which allows simply checking variables like myString.isNullOrEmpty().

Is there a way to combine such a check with a when expression? By default, the expression only allows explicit strings. Is something like this possible?:

when (myString) {
    "1" -> print("1")
    "2" -> print("1")
    myString.isNullOrEmpty() -> print("null or empty") //This is what I am looking for
    else -> print("None of them")
}

Solution

  • You can eliminate argument of when like this:

    when {
        myString == "1" -> print("1")
        myString == "2" -> print("2")
        myString.isNullOrEmpty() -> print("null or empty")
        else -> print("None of them")
    }
    

    Or explicitly say "null or empty string":

    when (myString) {
        "1" -> print("1")
        "2" -> print("2")
        null, "" -> print("null or empty")
        else -> print("None of them")
    }