QuintessentialGamer
QuintessentialGamer

Reputation: 51

Initializing class member to emptyList in secondary constructor

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){
    }
}

Upvotes: 1

Views: 39

Answers (2)

James Williams
James Williams

Reputation: 779

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

Upvotes: 3

Silvio Mayolo
Silvio Mayolo

Reputation: 70287

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()) {}

Upvotes: 3

Related Questions