Lalit Behera
Lalit Behera

Reputation: 540

How to assign new value if you setting the setter private in kotlin?

I am new in kotlin and not able to understand how the getter and setter behave in kotlin, so if I set the setter to private. Then what is the way of updating the value.

package foo

class Person() {
var name: String = "defaultValue"
   private set

}

Upvotes: 1

Views: 1139

Answers (2)

holi-java
holi-java

Reputation: 30696

the kotlin code above will be transform to java code by kotlin compiler more like as below:

package foo;
public final class Person{
  private String name = "defaultValue";

  public final String getName(){ 
      return name;
  }

  private final void setName(String name){
     this.name=name;
  }
}

which means you can only change the name field in the Person class. another situation is if you want to modify the name property with private setter out of the Person class. you can using java reflection instead, for example:

val person = Person();

val field = Person::name.javaField!!.apply { isAccessible = true }
field.set(person, "bob")
println(person.name)// "bob"

val setter = Person::class.java.getDeclaredMethod("setName", String::class.java)!!
                               .apply {
                                   isAccessible = true
                               }
setter.invoke(person, "john")
println(person.name)// "john"

Upvotes: 0

Januson
Januson

Reputation: 4861

If you set your setter to be private, then this setter will be accessible only from within its class. In other words you can use normal assignment even when your setter is private but only from within the class.

class Person() {
    var name: String = "defaultValue"
        private set

    fun foo(bar: String) {
        name = bar // name can be set here
    }
}

fun main(args: Array<String>) {
    Person().name = "foo" // error. Name can be accessed but can not be modified here as its setter is private.
}

For more information check the Kotlin's Visibility documentation.

Upvotes: 6

Related Questions