when(message) {
.startsWith("hey")
}
How do I check if my string starts with a certain word inside a switch statement in Kotlin?
You can use a when without an argument:
val msg = "This is some message"
when {
msg.startsWith("This") -> println("Starts with This")
msg.startsWith("That") -> println("Starts with That")
else -> println("Doesn't start with This or That")
}
Output:
Starts with This
This is really interesting question.
Maybe something like that, lol?
run {
operator fun String.unaryPlus() = "This is some message".startsWith(this)
when {
+"This" -> { println("Starts with This") }
+"That" -> { println("Starts with That") }
else -> { println("Doesn't start with This or That") }
}
}
run is for operator overload localization
Of course you can use function or extension function instead of operator.
fun String.a() = "This is some message".startsWith(this)
when {
"This".a() -> { println("Starts with This") }
"That".a() -> { println("Starts with That") }
else -> { println("Doesn't start with This or That") }
}
PS. And of course you can write all this as library code ))
class PredicateContext<T>(private val predicate: (T) -> Boolean) {
operator fun T.invoke() = predicate(this)
}
... and use it anywhere
PredicateContext<String> { "This is some message".startsWith(it) }.run{
when {
"This"() -> println("Starts with This")
"That"() -> println("Starts with That")
else -> println("Doesn't start with This or That")
}
}
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