0

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?

1
  • In Kotlin, there's an almost-universal convention that class names begin with a capital letter. If they don't, your code won't fail, but it will confuse most people reading it! Commented Jun 24, 2022 at 18:33

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Of course, if there's no more code to go into those secondary constructors, then this could be simplified much further by adding value to the primary constructor, with a default value of null — making the whole thing a one-liner! And/or you could parameterise its type, so that it would give the appropriate subclass type..
Thanks for the suggestion. Added this to the answer. From "parameterise its type", do you suggest using generics? Something like data class <T: ParentNode> Node(val type: String, val value: T? = null)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.