阻塞时在 Kotlin 中调用 String 方法
Calling String method in Kotlin when block
目前我有这样一个 when 块:
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*/ }
}
有什么方法可以将其简化为如下所示:
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*/ }
}
您可以使用 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")
}
}
试试这个:-
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}
}
}
目前我有这样一个 when 块:
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*/ }
}
有什么方法可以将其简化为如下所示:
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*/ }
}
您可以使用 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")
}
}
试试这个:-
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}
}
}