Mild spoilers in thread; mutable vs functional sty...
# advent-of-code
n
Mild spoilers in thread; mutable vs functional style for a non-trivial data transformation, curious to see which people think is more readable
Copy code
val parentMap: Map<String, List<String>> = mutableMapOf<String, MutableList<String>>().apply {
        getData().forEach { rule ->
            rule.contained.forEach {
                getOrPut(it.name) { mutableListOf() }.add(rule.containing)
            }
        }
    }
compared to
Copy code
val parentMap2 = getData().asSequence()
        .map { rule -> rule.contained.asSequence().map { it.name to rule.containing}}.flatten()
        .groupBy(keySelector = {it.first}, valueTransform = {it.second})
    val bagSet = mutableSetOf<String>()
Where:
Copy code
data class ContainedBag(val num: Int, val name: String)
data class Rule(val containing: String, val contained: List<ContainedBag>)
fun getData(): List<Rule> { ... }
In the end the imperative/mutable and functional solutions seem comparable in length, but I had to think a lot more to put the functional solution together.
The mutable solution I knew what to do immediately. For the functional solution I really had to spend around 5 minutes looking at what was available, seeing that groupBy couldn't do what I needed on its own, realizing that I had to create nested sequences and flatten... a lot more brainpower to achieve the same result. Curious if other folks feel the same or differently
j
Yeah, for me the mutable version is far easier to parse