阻止时在Kotlin中调用String方法

Col*_*onD 4 syntax android kotlin kotlin-when

目前,我有一个when块,像这样:

String 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*/ }
}
Run Code Online (Sandbox Code Playgroud)

有什么办法可以简化为这样的事情:

String 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*/ }
}
Run Code Online (Sandbox Code Playgroud)

Nil*_*hod 5

您可以使用 with

试试这个

    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")
        }
    } 
Run Code Online (Sandbox Code Playgroud)