“Getter and Setter di Kotlin” Kode Jawaban

getters dan setters Kotlin

Getters and setters are auto-generated in Kotlin. If you write:

val isEmpty: Boolean
It is equal to the following Java code:

private final Boolean isEmpty;

public Boolean isEmpty() {
    return isEmpty;
}
In your case the private access modifier is redundant - isEmpty is private by default and can be accessed only by a getter. When you try to get your object's isEmpty property you call the get method in real. For more understanding of getters/setters in Kotlin: the two code samples below are equal:

var someProperty: String = "defaultValue"
and

var someProperty: String = "defaultValue"
    get() = field
    set(value) { field = value }
Also I want to point out that this in a getter is not your property - it's the class instance. If you want to get access to the field's value in a getter or setter you can use the reserved word field for it:

val isEmpty: Boolean
  get() = field
If you only want to have a get method in public access - you can write this code:

var isEmpty: Boolean
    private set 
due to the private modifier near the set accessor you can set this value only in methods inside your object.
android developer

Getter and Setter di Kotlin

Getters and setters are auto-generated in Kotlin. If you write:

val isEmpty: Boolean
It is equal to the following Java code:

private final Boolean isEmpty;

public Boolean isEmpty() {
    return isEmpty;
}
In your case the private access modifier is redundant - isEmpty is private by 
default and can be accessed only by a getter. When you try to get your object's 
isEmpty property you call the get method in real. For more understanding of 
getters/setters in Kotlin: the two code samples below are equal:

var someProperty: String = "defaultValue"
and

var someProperty: String = "defaultValue"
    get() = field
    set(value) { field = value }
Also I want to point out that this in a getter is not your property - 
it's the class instance. If you want to get access to the field's value 
in a getter or setter you can use the reserved word field for it:

val isEmpty: Boolean
  get() = field
If you only want to have a get method in public access - you can write this code:

var isEmpty: Boolean
    private set 
due to the private modifier near the set accessor you can set this value only 
in methods inside your object.
android developer

Kotlin Bagaimana Getters dan Setter bekerja?

class Person {
    var name: String = "defaultValue"

    // getter
    get() = field

    // setter
    set(value) {
        field = value
    }
}
SAMER SAEID

Jawaban yang mirip dengan “Getter and Setter di Kotlin”

Pertanyaan yang mirip dengan “Getter and Setter di Kotlin”

Lebih banyak jawaban terkait untuk “Getter and Setter di Kotlin” di Kotlin

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya