[在阻止时在Kotlin中调用String方法

问题描述 投票:4回答:2

当前我有一个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*/ }
}

有没有办法将其简化为类似这样的内容:

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*/ }
}
android kotlin syntax kotlin-when
2个回答
4
投票

您可以使用with

尝试这种方式

with

-1
投票

请尝试:-

    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")
        }
    } 
© www.soinside.com 2019 - 2024. All rights reserved.