Currently I have a when block like this:
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*/ }
}
Is there any way to simplify this to something like this:
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*/ }
}
:: converts a Kotlin function into a lambda. this translates to MyClass(x, y) in Kotlin.
Before you can use (call) a function, you need to define it. To define a function in Kotlin, fun keyword is used. Then comes the name of the function (identifier). Here, the name of the function is callMe .
it can be used without an argument.
You can use with
Try this way
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")
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With