JoeGalind
JoeGalind

Reputation: 3805

Kotlin Recursive Structure

I need the following structure:

val menu = Information("0100", "About us", {
    Information("0101", "Welcome!"),
    Information("0102", "Our History"),
    Information("0103", "Our Values"),
    Information("0104", "Guest Services"),
    Information("0105", "Others", {
        Information("106", "Foo")
    }
}),

Right now, I have the class Information as so:

class Information(id: String,  name: String,  subCategories: Array<Information>?) {

}

Buy it is not compiling. I would like to know what the correct syntax would be for this, or if anyone could suggest the best approach for this.

Upvotes: 0

Views: 107

Answers (1)

Tenfour04
Tenfour04

Reputation: 93629

You need to use the proper syntax for declaring arrays:

val menu = Information(
    "0100", "About us", arrayOf(
        Information("0101", "Welcome!"),
        Information("0102", "Our History"),
        Information("0103", "Our Values"),
        Information("0104", "Guest Services"),
        Information(
            "0105", "Others", arrayOf( Information("106", "Foo") )
        )
    )
)

And you need a default value for the array for when there are no subcategories, if you don't want to have to pass null:

class Information(val id: String, val name: String, val subCategories: Array<Information>? = null)

Upvotes: 1

Related Questions