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

Viewed 21856

I am new to kotlin, I have tried several ways to use following code

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

In above code strAction.contains("Grid") this line is showing me an error that Incompatible Type

enter image description here

6 Answers

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)

Try this remove when(strAction) parameter from when

val strAction = "Grid"    

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

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.

The other answers explain how to fix the problem but not what the problem actually is. Your code calculates strAction.contains("Grid") (which will be a Boolean) and then compares strAction with this value. I.e. it's equivalent to

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

They can't be equal because the types are incompatible, so this branch could never be taken and the compiler tells you this.

You can use Kotlin in

if ("Grid" in strAction) { println("position is 1") }
Related