I'm looking for a way to make this more idiomatic....
# announcements
a
I'm looking for a way to make this more idiomatic. It's not the best solution, but it works at the moment. I'm looking to learn more about collection transformations and how I could possibly do this with built in Kotlin functions. Can anyone point me in the direction on maybe what functions (map, etc) I should be looking into? Thank you!
Copy code
fun main() {

    val list = """
        a,234,97654/
        b,23,ABC,
        b,44235,203
        a,234,97654/
        b,23,ABC
        b,44235,203
        49,234
        39,9291
    """.trimIndent().split("\n")

    var total = mutableListOf<String>()

    for ((index, value) in list.withIndex()){

        var sb = StringBuilder()

        var nextIndex = index

        if(value.startsWith("a") && value.endsWith("/")) {
            sb.append(value)

            while(list[nextIndex + 1].startsWith("b")) {
                sb.append(list[nextIndex + 1])
                nextIndex++
            }

            total.add(sb.toString())
        }
    }
}
j
There are a few approaches you can take. For this particular problem, the three most important will be
fold
,
takeWhile
and
flatten
though there is more than one valid approach. This problem is a little tricky since your handling is context sensitive.
a
Thanks for the reply Jakub! I'll take a look at those three and see if I can put something together.
j
I had answered a similar problem a few days ago, you may get some ideas: https://kotlinlang.slack.com/archives/C0922A726/p1588550363382900
You can probably modify it slightly to do the first step (splitting of your list), and from there you can just flatMap/dropWhile to get to the final answer
functional solution
Kind of sad that my solution ended up not using any of the functions I recommended 😕
m
this particular problem I'd solve with regex btw
can be cleanish without regex too
a
Very helpful on all fronts. Thank you all for your replies!
j
If you are going to use a string builder, I'd suggest using buildString{} where possible, it will make the code cleaner
@Michael de Kaste Your solution will act differently from the original if there is an entry starting with a number between the a.\/ and b. entries
a
@Jakub Pi That's correct. Essentially I need the solution to only add the b values to the string if the entry started with 'a' first. A1, b4, b34 X b99 Ab9 B0 Should only return two values in the list. A1,b4,b34 Ab9,B0