I have tried to set a property value as in the following snippet.This SO question is not answering the question.
var person = Person("john", 24)
        //sample_text.text = person.getName() + person.getAge()
        var kon = person.someProperty
        person.someProperty = "crap" //this doesn't allow me to set value
        kon = "manulilated"  //this allows me to set the value
        sample_text.text = kon
class Person(val n: String, val a: Int){
    var pname: String = n
    var page: Int = a
    var someProperty: String = "defaultValue"
        get() = field.capitalize()
        private set(value){field = value}
    fun Init(nm: String, ag: Int){
        pname = nm
        page = ag
    }
    fun getAge(): Int{
        return page
    }
    fun getName(): String{
        return pname
    }
}
Why was I able to set the value of the Person class on the second line but not the first line?
First, the private modifier is your problem.
Change
private set(value){field = value}
To
set(value){field = value}
//public by default
Otherwise you can’t use the setter outside the class. Read here.
For members declared inside a class: private means visible inside this class only (including all its members);
Second, you’re misunderstanding something:
 var kon = person.someProperty
 kon = "manulilated" 
In these lines you’re not changing the property in the object. After creating the variable kon, being a String pointing to someProperty, you reassign that local variable to something else. This reassignment is unequal to changing the value of person.someProperty! It has totally no effect in the object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With