KOTLIN TIP #2

CUSTOM GETTERS/SETTERS

Kotlin’s custom getters and setters use the structure of a model, but specify custom behavior to get and set the fields. When using custom models for certain frameworks, such as the Parse SDK, you are fetching values that are not actually local variables in the class but are stored and retrieved in some custom way, such as from JSON. By using custom-defined getters and setters, we can simplify the access:

@ParseClassName("Product")
class Product : ParseObject() {

    // getString() and put() are methods that come from ParseObject
    var name: String
        get() = getString("name")
        set(value) = put("name", value)

    var description: String
        get() = getString("description")
        set(value) = put("description", value)
}

Fetching these values would look similar to using property access syntax with other models:

val product = api.getProduct()
textDesciption.text = product.description

Now if your model needed to change from Parse to some other data source, your code would potentially only need to be changed in one place.

 

Leave a comment