So I have a String i would want to check if I should split into two, or return some default value. Like this:
val myString = "firstPart-secondPart"
val (first, second) = when (myString.contains("-")) {
true -> myString.split('-', limit = 2)
else -> ?? <-- How would i return ("Default1", "Default2") so the destructuring still works?
}
So my question is, how do i return two default strings, so that the deconstructing works? I've used String.split()
before in order to deconstruct and it's really nice.
As an alternative to the good and correct answer of jrtapsell, you could use destructured Pair
s:
val (first, second) = when (myString.contains("-")) {
true -> myString.split('-', limit = 2).let { it[0] to it[1] }
else -> "Default1" to "Default2"
}
Note 1: The resulting list with two elements is transformed to a Pair
with the help of let
.
Note 2: The infix function to
is used to create Pair
s here.
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