Meet Maheshwari
Meet Maheshwari

Reputation: 140

Kotlin : How to access private data members of class by their objects?

How do I access p.name by its object if it private?

Getter and setter don't work here.

class Person(f_name : String, l_name : String){
    private var name = f_name + l_name
    get() = field
    set(value) {
        field = value
    }
    private var age : Int? = null
        get() {
            println("Age getter")
            return field
        }
        set(value) {
            println("Age setter")
            field = value
        }
    constructor(f_name: String, l_name: String, age : Int):this(f_name, l_name){
        name = "Mr./Msr./Ms. $f_name $l_name"
        this.age = age
    }

}

fun main() {
    var p = Person("M", "M")
    var m = Person("P", "P", 20)

    println("p : Person(${p.name})") // Shows error here

}

I cannot access any private member in this way. There is no use of getter and setter here.

Upvotes: 1

Views: 3379

Answers (2)

Yawar
Yawar

Reputation: 1046

Remove private from property and set it to accessor. It will make it visile to other classes as readonly property whereas can only be set with in its own class.

var name = f_name + l_name
    private set(value) {
        field = value
    }

Upvotes: 1

tynn
tynn

Reputation: 39843

You might want to approach this with an immutable data class. Then setters are unnecessary and getters can be public:

data class Person(
    val firstName: String,
    val lastName: String,
    val age: Int? = null
)

The complete name you could define as an extension property then:

val Person.name get() = "Mr./Msr./Ms. $firstName $lastName"

As a default private properties are not accessible, but you can restrict access of a setter if you like:

var name: String = ""
    private set

In general a property is a getter and maybe a setter accessing a field. The field is never public. Therefore to achieve what you want, you only need to declare the property as var name: String.

Upvotes: 4

Related Questions