https://kotlinlang.org logo
Title
b

b00m

07/12/2019, 12:38 PM
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

kralli

07/12/2019, 1:01 PM
Thats very confusing. Can you please be more specific?
b

b00m

07/12/2019, 1:07 PM
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

kralli

07/12/2019, 1:10 PM
And now you’re looking for a way to represent it in your code?
b

b00m

07/12/2019, 1:11 PM
right well i dont know how to define a type that would represent that
k

kralli

07/12/2019, 1:14 PM
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.
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:
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

b00m

07/12/2019, 2:02 PM
thankyou, i'll study your code fragment and see what i learn