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
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.
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.
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") }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With