Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

starts with inside switch statement Kotlin

when(message) {
    .startsWith("hey")
}

How do I check if my string starts with a certain word inside a switch statement in Kotlin?

like image 651
paspielka Avatar asked Feb 12 '26 10:02

paspielka


2 Answers

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
like image 99
deHaar Avatar answered Feb 15 '26 11:02

deHaar


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")
    }
}
like image 30
sirjoga Avatar answered Feb 15 '26 12:02

sirjoga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!