在我的代码中,我有以下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中有没有做类似事情的方法?
最佳答案
快捷又脏的
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
的答案更好。