Home > Software engineering >  Initializing class member to emptyList in secondary constructor
Initializing class member to emptyList in secondary constructor

Time:12-05

I'm very new to Kotlin and have to implement a data class TreeNode that resembles a generic tree of nodes. I'm trying to declare a secondary constructor that initializes the member children to be an empty list. Here's what I tried; but I'm not understanding the syntax quite well so not sure how to go about solving this.

data class TreeNode<T> (
    val value: T,
    val children: List<TreeNode<T>>,
) {

    constructor(value: T, children: emptyList<TreeNode<T>>): this(value){
    }
}

CodePudding user response:

You're getting confused by where to put the arguments. If you know the list is empty, you don't need to take it as an argument.

constructor(value: T): this(value, emptyList()) {}

CodePudding user response:

In addition to Silvio's answer, if you want to be able to take a list of children but default to not doing so:

data class TreeNode<T>(val value: T, val children: List<TreeNode<T>> = emptyList()) {}

See the section on default values in constructors in the Kotlin documentation: https://kotlinlang.org/docs/classes.html#constructors

  • Related