kotlinif-statementconditional-statementscasekotlin-when

when condition with ignore case in kotlin


I know we can write if, else if, else if with a ignore case.

if (someString.equals("otherString", ignoreCase = true)) {
}

I am very curious about this, how to write a when(in Java it is a switch) condition with ignoring the case.


Solution

  • There are a couple of options:

    1. Translate strings to lower (or upper) case:

      when (someString.toLowerCase()) {
          "otherString1".toLowerCase() -> { /*...*/ }
          "otherString2".toLowerCase() -> { /*...*/ }
      }
      
    2. Directly use equals method:

       when {
           someString.equals("otherString1", ignoreCase = true) -> { /*...*/ }
           someString.equals("otherString2", ignoreCase = true) -> { /*...*/ }
       }