Helen
Helen

Reputation: 3

Secondary constructor in Kotlin

I have 2 secondary constructors for a data class.

data class node(var type: String):parentNode(){
    constructor(type: String, value: aNode) : this(type)
    constructor(type: String, value: bNode) : this(type)
}

I want to return a value from a function which is node(type:String, value:aNode).

fun getNode(): node{
val aNode = getAnode
val type = "Bank"
val return_val = node(type,aNode)
return (return_val)}

a = getNode()

Now 'a' has only the 'type' but not 'aNode'. Any idea on what am i missing here?

Upvotes: 0

Views: 1041

Answers (1)

Arpit Shukla
Arpit Shukla

Reputation: 10523

This is because value is not a property of node class. It is just a constructor argument. You need to put it as a property first and then initialize it from the constructor.

data class node(var type: String): parentNode() {
    
    var value: parentNode? = null // Assuming aNode and bNode inherit from parentNode

    constructor(type: String, value: aNode) : this(type) {
        this.value = value
    }
    
    constructor(type: String, value: bNode) : this(type) {
        this.value = value
    }
}

Now you will be able to access this value using a.value. If the node class is instantiated using the primary constructor, a.value will be null.

Also, you might want to add private set to this value property so that it cannot be modified from outside. You can do the same with the type property (make it a val). Most of the times you would want to use val properties in a data class instead of vars.

(And it is recommended to follow Kotlin's naming conventions while creating variables, classes, functions, etc.)

Edit: As @gidds suggested, you can also include the value property in the primary constructor with a default value null and get rid of those secondary constructors.

data class node(val type: String, val value: parentNode? = null)

Upvotes: 1

Related Questions