Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin Destructuring when/if statement

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.

like image 851
Robin Jonsson Avatar asked Mar 13 '18 12:03

Robin Jonsson


1 Answers

As an alternative to the good and correct answer of jrtapsell, you could use destructured Pairs:

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 Pairs here.

like image 66
s1m0nw1 Avatar answered Nov 11 '22 19:11

s1m0nw1