I'm wondering if it's possible to define a type th...
# getting-started
b
I'm wondering if it's possible to define a type that would like a collection of either a String or another collection of possibly strings or Collections
k
Thats very confusing. Can you please be more specific?
b
im writing a function to process a string into an AST, which is a collection of primitives or collections
the types for example are [1 3 3 [434 3]]
k
And now you’re looking for a way to represent it in your code?
b
right well i dont know how to define a type that would represent that
k
Well, sealed classes might help you out here. Or generally speaking ASTs are usually implemented using concrete classes for each possible type in the tree.
Copy code
sealed class Tree {
    
    data class Leaf(val value: String) : Tree()
    data class Node(val children: List<Tree>) : Tree()
}
Then you can work with the tree either using visitors or simply
when
expressions:
Copy code
fun stringRepresentation(tree: Tree): String {
    return when (tree) {
        is Tree.Leaf -> tree.value
        is Tree.Node -> tree.children.joinToString(separator = " ", prefix = "[", postfix = "]") { stringRepresentation(it) }
    }
}
b
thankyou, i'll study your code fragment and see what i learn