Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling String method in Kotlin when block

Currently I have a when block like this:

val foo = getStringFromBar()

when {
    foo == "SOMETHING" -> { /*do stuff*/ }
    foo == "SOMETHING ELSE" -> { /*do other stuff*/ }
    foo.contains("SUBSTRING") -> { /*do other other stuff*/ }
    else -> { /*do last resort stuff*/ }
}

Is there any way to simplify this to something like this:

val foo = getStringFromBar()

when (foo) {
    "SOMETHING" -> { /*do stuff*/ }
    "SOMETHING ELSE" -> { /*do other stuff*/ }
    .contains("SUBSTRING") -> { /*do other other stuff*/ }  // This does not work
    else -> { /*do last resort stuff*/ }
}
like image 424
ColonD Avatar asked Sep 25 '19 07:09

ColonD


People also ask

What does :: mean in Kotlin?

:: converts a Kotlin function into a lambda. this translates to MyClass(x, y) in Kotlin.

How do I call a method in Kotlin?

Before you can use (call) a function, you need to define it. To define a function in Kotlin, fun keyword is used. Then comes the name of the function (identifier). Here, the name of the function is callMe .

Can when statement in Kotlin be used without passing any argument?

it can be used without an argument.


1 Answers

You can use with

Try this way

    with(foo) {
        when {
            equals("SOMETHING") -> println("Case 1")
            equals("something",false) -> println("Case 2")
            contains("SUBSTRING") -> println("Case 3")
            contains("bar") -> println("Case 4")
            startsWith("foo") -> println("Case 5")
            else -> println("else Case")
        }
    } 
like image 174
AskNilesh Avatar answered Sep 19 '22 15:09

AskNilesh