Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Kotlin – Setter for Properties Initialized in Constructor?

hope I worded this right. Trying to be able to do a setter function for a variable that is initialized in a constructor ala:

package com.example.propory

class Property(val name: String, propValue: String) {

    var previousPropertyValue: List<String> = listOf("testing")

    var propValue: String = ""
        set(value){
            previousPropertyValue += this.propValue
            field = value
        }
}

I can access "name" just fine outside of this when I create a instance of it ala:

// trunicated
 val currentProperty = Properties.find { prop -> property.name == prop.name}

however if I try to access "propValue":

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

currentProperty.propValue = property.propValue

I don’t get any value :(.

So wondering what I did wrong and how to fix it. Thank you all for the help! 🙂

>Solution :

You’re leaving the propValue parameter that is passed into the constructor completely unused, and initializing your property with an empty String. Initialize it with the parameter that was passed into the constructor:

var propValue: String = propValue
    set(value){
        previousPropertyValue += this.propValue
        field = value
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading