43

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

1
  • 2
    I dont understand why there is downvote Nov 23, 2017 at 4:39

6 Answers 6

82

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)
1
  • 5
    Thanks that's the best reply imo, there is a way to "factorise" the "contains" so i don't need to type it every line if I only want contains directive ?
    – safepost
    Apr 9, 2019 at 12:43
50

Try this remove when(strAction) parameter from when

val strAction = "Grid"    

when {
  strAction.contains("Grid") -> println("position is 1")
}
2
  • 1
    Thanx for your help but it didn't worked for me still facing same issue Nov 22, 2017 at 12:25
  • 1
    @YoLo remove strAction from when no need to pass that
    – Goku
    Nov 22, 2017 at 12:41
3

You don't need to pass strAction

val strAction = "Grid"

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

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.

0

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.

0

You can use Kotlin in

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.