Unable to use string.contains() in kotlin `when` expression

Try this remove when(strAction) parameter from when

val strAction = "Grid"    

when {
  strAction.contains("Grid") -> println("position is 1")
}

You can also combine when and with to get a nice syntax:

with(strAction) {
  when {
    contains("Grid") -> println("position is 1")
    contains("bar") -> println("foo")
    startsWith("foo") -> println("bar")
    else -> println("foobar")
  }
}

You can also save the result of when into a property:

val result = with(strAction) {
  when {
    contains("bar") -> "foo"
    startsWith("foo") -> "bar"
    else -> "foobar"
  }
}

println(result)

You don't need to pass strAction

val strAction = "Grid"

 when {
   strAction.contains("Grid") -> println("position is 1")
 }
}

If there's only one case in your when, I'd recommend to use if instead. That's already what you're trying to do there:

val strAction = "Grid"
if (strAction.contains("Grid")) {
   println("position is 1")
}

Even shorter, isn't it?

Just for the record: You switch on a String (in when) but have Boolean cases, which won't work. What would do the trick, though:

val strAction = "Grid"
when (strAction.contains("Grid")) {
   true->println("position is 1")
}

But again, do if.

Tags:

Android

Kotlin