做一个简短的if语句

时间:2017-12-11 21:22:33

标签: android if-statement kotlin

在我的代码中,我有这个if语句:

if (categoryName == "SomeName1" || categoryName == "SomeName2" || 
    categoryName == "SomeName3" || categoryName == "SomeName4" || 
    categoryName == "SomeName5" || categoryName == "SomeName6") {
    // Do something
}

我想知道是否可以缩短这个时间。类似的东西:

if (categoryName == "SomeName1" and "SomeName2" and "SomeName3" ...) {
    // Do something
}

Kotlin有没有办法做这样的事情?

5 个答案:

答案 0 :(得分:4)

又快又脏

if (Arrays.asList("SomeName1", "SomeName2", "SomeName3", "SomeName4", "SomeName5", "SomeName6").contains(categoryName)) {
    // Do something
}

<强>更好

val myList = Arrays.asList("SomeName1", "SomeName2", "SomeName3", "SomeName4", "SomeName5", "SomeName6");
if (myList.contains(categoryName)) {
    // Do something
}

修改 Voddan使用setOf的答案更好。

答案 1 :(得分:4)

您可以使用when语句。语法类似于你所要求的:

when (categoryName) {
    "SomeName1", "SomeName2",  "SomeName3", "SomeName4", "SomeName5", "SomeName6" -> // Do something
}

答案 2 :(得分:3)

switch语句怎么样?

switch(categoryName) {
    case "SomeName1":
    case "SomeName2":
    case "SomeName3":
    case "SomeName4":
    case "SomeName5":
    case "SomeName6":
        // Do something
        break;
    default: 
        // Do something else
        break;
}

答案 3 :(得分:3)

您可以考虑使用正则表达式:

if (categoryName.matches(Regex("SomeName[1-6]"))) {
    // Do something
}

答案 4 :(得分:2)

最基本的解决方案IMO:

val names = setOf("SomeName1", "SomeName2", "SomeName3", "SomeName4", "SomeName5", "SomeName6")

if (categoryName in names) {
    // Do something
}

它利用哈希集中的搜索,因此在某些条件下它也可能是最快的解决方案。