``` class Day08(rawInput: String) { private va...
# advent-of-code
t
Copy code
class Day08(rawInput: String) {
    private val tree: Node = Node.of(rawInput.split(" ").map { it.toInt() }.iterator())

    fun solvePart1(): Int =
        tree.metadataTotal

    fun solvePart2(): Int =
        tree.value

    private class Node(children: List<Node>, metadata: List<Int>) {
        companion object {
            fun of(values: Iterator<Int>): Node {
                val numChildren: Int = values.next()
                val numMetadata: Int = values.next()
                val children = (0 until numChildren).map { Node.of(values) }
                val metadata = (0 until numMetadata).map { values.next() }.toList()
                return Node(children, metadata)
            }
        }

        val metadataTotal: Int =
            metadata.sum() + children.sumBy { it.metadataTotal }

        val value: Int =
            if (children.isEmpty()) metadata.sum()
            else metadata.map { children.getSafely(it)?.value ?: 0 }.sum()

        private fun List<Node>.getSafely(i: Int): Node? =
            if (i > this.size) null
            else this[i - 1]

    }
}
t
For my culture, in what case would you use a companion Object ?
t
Think of a companion object as where you would put static methods if you were doing this in java. So in this case I have
Node.of(...)
that people can use. The
of
is "static" in a sense. Another good use for companion objects are for loggers (need only one per type), constants, things of that nature. Does that help you?
k
Although Java static methods can also be done with top level Kotlin functions, so it's not straight
static
->
companion
.
t
Yes, so true. Hard to get away from old habits sometimes.
t
Ok I see, thank you. I'm doing Python right now, that's why such things are blurry !