[Custom Accessor] Make Getter more simple with Kotlin



Let’s say you already know about getter and setter of Java.
The Accessors are like this:

class Pizza {
    private int radius;
    
    public void setRadius(int radius) {
        this.radius = radius;
    }
    
    public int getRadius() {
        return radius;
    }
}


In Kotlin, it is really simple!

class Pizza(var radius: Int)

That’s it! It is same with above Java code. property radius makes itself getter and setter internally.(If you want to make only getter, val radius: Int)



Let’s define ‘large size’ if its radius longer than 20.

To check if a pizza is large size or not, you could add a property like val isLargeSize: Boolean = true or val isLargeSize: Boolean = false

But Custom Accessor makes it even more simple.

class Pizza(var radius: Int) {
    val isLargeSize get() = radius>20
}

It doesn’t need field that save its value. Getter calculate isLargeSize everytime client access to the property.



Moreover you can use this for some util function.

val Int.isEven get() = this%2==0

val String.hasUpperCase: Boolean get() {
    this.forEach { 
        if(it.isUpperCase()) return true
    }
    return false
}


//usage
println("Is 6 even number? ${6.isEven}")    //true
println("macbook has uppercase? ${"macbook".hasUpperCase}"  //false





If there’s a mistake, always welcome your opinion!


</br>

android

Back to Top ↑

kotlin

Back to Top ↑

progressBar

Back to Top ↑

compose

Back to Top ↑

editText

Back to Top ↑