Calling String method in Kotlin when block
Asked Answered
G

2

5

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*/ }
}
Ginelle answered 25/9, 2019 at 7:3 Comment(0)
E
6

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")
        }
    } 
Extemporize answered 25/9, 2019 at 7:9 Comment(0)
B
0

try this:-

 with(foo) {
    when {
        equals("SOMETHING") -> { //do stuff}
        equals("something",false) -> { //do stuff}
        contains("SUBSTRING") -> { //do stuff}
        contains("bar") -> { //do stuff}
        startsWith("foo") -> { //do stuff}
        else -> { //do stuff}
    }
} 
Babineaux answered 25/9, 2019 at 7:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.