1

I am new in programming and especially in Kotlin, I am sorry if my question is too basic

I need to make a property can be mutated only inside its class, but if other class access that property, I can only get the value but can't change it.

class Person {

    var name = ""

    fun changeName(newName: String) {
        name = newName
    }


}

but if I access this from other class, I still can change the name. I only want to get the value if it is accessed from other class

somePerson.name = "newNameIsNotAllowedHere"

but if I change the property to val then I am confused how to assign via method

class Person {

    val name = ""

    fun changeName(newName: String) {
        name = newName // can't assign new value because of val
    }


}

if using LiveData in Android, from tutorial I follow, I can do something like this, but I am confused how to apply the same behaviour in normal data type

    private val mIsLoadingData = MutableLiveData<Boolean>()
    val isLoadingData : LiveData<Boolean>
        get() =  mIsLoadingData
sarah
  • 3,819
  • 4
  • 38
  • 80

1 Answers1

0

Pubic getter and a private setter:

class Person {

    var name: String = ""
        private set

}

Docs: http://kotlinlang.org/docs/reference/properties.html#getters-and-setters

Jared Burrows
  • 54,294
  • 25
  • 151
  • 185