Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

android

kotlin

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

like image 690
yogesh lokhande Avatar asked Nov 22 '17 12:11

yogesh lokhande


People also ask

How do I use string contains in Kotlin?

To check if a string contains specified string in Kotlin, use String. contains() method. Given a string str1 , and if we would like to check if the string str2 is present in the string str1 , call contains() method on string str1 and pass the the string str2 as argument to the method as shown below.

How do you declare strings in Kotlin?

To declare a string in Kotlin, we need to use double quotes(” “), single quotes are not allowed to define Strings. Creating an empty String: To create an empty string in Kotlin, we need to create an instance of String class.


2 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) 
like image 73
Brian Avatar answered Sep 28 '22 21:09

Brian


Try this remove when(strAction) parameter from when

val strAction = "Grid"      when {   strAction.contains("Grid") -> println("position is 1") } 
like image 31
Goku Avatar answered Sep 28 '22 20:09

Goku