Home > Enterprise >  Kotlin to filter certain options using When
Kotlin to filter certain options using When

Time:04-23

How can I use When in Kotlin to do something if not in some certain conditions? for example

  when(condition : String){
    //not "A","B","C" -> return
    // else -> continue to do something
}

I've tried some keyword or operator such as ! or not, but doesn't work

CodePudding user response:

For the specific case in your question, here are two ways I would do it:

when (myString) {
    !in arrayOf("A", "B", "C") -> return
    else -> {
        // continue to do something
    }
}

Just flipping the condition (swap the order of your code):

when (myString) {
    "A", "B", "C" -> {
        // continue to do something
    }
    else -> { }
}

CodePudding user response:

if not in some certain conditions?

Exactly that.

let's suppose you have this :

  val value  = 5 

to check if something is within a certain range of values:

      when (value in 0..5) {
        true -> {}
        else -> {}
    }

alternatively:

    when (value !in 0..5) {
        true -> {}
        else -> {}
    }

but making use of negative logic is sometimes harder to read or follow, so the first approach would probably be easier to understand perhaps.

similary for strings:

 val range = arrayListOf("a", "b", "c")
    when (value in range) {
        true -> {}
        else -> {}
    }

you could also expand this further:

  val value = "hello"

    val allowedRange = arrayListOf("a", "b", "c")
    val excludedRange = arrayListOf("x", "y", "z")
    when (value) {
        in allowedRange -> {

        }

        in excludedRange -> {

        }
        else -> {}
    }
  • Related