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

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)

Leave a Comment