title: How to deal with recursive and nested data classes in Kotlin
body: <p>In my application, I am getting a JSON response from an API which I need to parse it.
  The JSON looks like this:</p>
  
  <pre><code>{
  "itemTemplates":
  [
    {
      "type": "...",
      "properties": {
        "..": ".."
      },
      "children": [
        {
          "type": "..",
          "properties": {
            "..": ".."
          },
          "children": [
            {
              "type": ".."
            }
          ]
        },
        {
          "type": "..",
          "properties": {
            "value": ".."
          }
        },
        {
          "type": "..",
          "properties": {
            "value": ".."
          }
        }
      ]
    }
  ]
  </code></pre>
  
  <p>}</p>
  
  <p>I have created Kotlin data classes for the above response which looks like this:</p>
  
  <pre><code>data class ItemTemplate(val itemTemplates: List&lt;Component&gt; = listOf())
  
  
  data class Component(
  val children: List&lt;Children&gt; = listOf(),
  val Properties: Properties = Properties(),
  val type: String = "")
  
  
  data class Children(
  val properties: Properties = Properties(),
  val type: String = "",
  val children: List&lt;Children&gt; = listOf())
  </code></pre>
  
  <p>As you can see there is a recursive data class in the Children data class. In the JSON response, each Child can have many or zero Children itself.
  The problem occurs when it comes to using the data classes. i.e. I cannot loop over Children because it may also have Children which I need to iterate over that as well (and so on).</p>
  
  <p>Since it is not known which Child has Children and how many times I should iterate in order to parse everything, I started thinking of maybe using a recursive function. However, not sure if it is correct to do so and how to do it.</p>
  
  <p>Any suggestions?
  Thanks</p>