https://kotlinlang.org logo
#getting-started
Title
# getting-started
y

Yousef

09/28/2021, 3:26 PM
I'm not sure if this is the place to ask and might not be kotlin specific, but if I want a category with a list of subcategories, but I don't want the subcategories to have their own subcategories, how do I do that?
Copy code
data class Category(
    val id: UUID,
    var title: String,
    var slug: String,
    var subCategories: List<Category>
)
p

Paul Griffith

09/28/2021, 3:30 PM
One option is distinct (sealed) types with a common interface
1
y

Yousef

09/28/2021, 3:32 PM
That's exactly what I was trying to figure out thank you so much!
t

Tobias Berger

09/28/2021, 3:36 PM
I'd say using a sealed interface is somewhat optional here. You could also use a normal interface. but that could be a bit ugly because of the type of your
subcategories
property. If you don't need data classes, another option is to have a simple Category class without the subcategories and another "TopLevelCategory" class that inherits from it and adds the subcategories list. All a matter of style and preference, I myself would also go with the approach mentioned by @Paul Griffith
2
y

Yousef

09/28/2021, 3:40 PM
I'll keep that in mind thank you
2 Views