Kotlin (4): Getters and Setters

Properties in Kotlin

var author: String = "Steven"


This is the same as defining the following get() and set() methods:

(example 1:)

var author: String = "Steven"

    get() {

        return field

    }

    set(value) {

        field = value

    }

---

(example 2:)

class Rectangle(val width: Int, val height: Int) {

    val area: Int // property type is optional since it can be inferred from the getter's return type

        get() = this.width * this.height

}

---

(example 3:)

var stringRepresentation: String

    get() = this.toString()

    set(value) {

        setDataFromString(value) 

    }


----

Backing fields:

Every property we define is backed by a field that can only be accessed within its get() and set() methods using the special field keyword.

(example:)

var counter = 0 

    set(value) {

        if (value >= 0) field = value

    }

or

var rating: Int = 5 get() { if (field < 5) { print("Warning: this is a terrible book") } return field } set(value) { field = when { value > 10 -> 10 value < 0 -> 0 else -> value } }

---








留言

這個網誌中的熱門文章

最爛的銀行服務-玉山銀行

SMR疊瓦式hdd致命缺陷被解決????!!!

更改google drive預設存放目錄位置Change Google Drive Default Folder Location in Windows

ios app 上架時app icon要注意事項

Mark App Design Apps - Terms and Privacy Policy (服務條款,隱私權政策)

Gmail 永久刪除大型電子郵件

app bundle and bundletool. 關於aab安裝問題

關於google play console app應用程式簽署

來談談admob廣告政策違規的不好體驗

舊有app在Android 12 閃退問題& app Splash screens