### 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 } }

---
{"ft_lang_label":"__label__en","ft_lang_prob":0.6126882,"math_prob":0.9641051,"size":989,"snap":"2023-14-2023-23","text_gpt3_token_len":270,"char_repetition_ratio":0.14111675,"word_repetition_ratio":0.045454547,"special_character_ratio":0.32355917,"punctuation_ratio":0.116959065,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.95030445,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2023-06-10T12:06:04Z\",\"WARC-Record-ID\":\"<urn:uuid:2129bce0-bb75-477d-b261-fae320199b17>\",\"Content-Length\":\"215245\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:89a078a2-91e3-44c6-9a90-361c31d735de>\",\"WARC-Concurrent-To\":\"<urn:uuid:e5a02a51-9904-41f3-9fce-3b7ed04aa8d3>\",\"WARC-IP-Address\":\"172.253.63.132\",\"WARC-Target-URI\":\"https://markappdesign.blogspot.com/2022/06/kotlin-5-getters-and-setters.html\",\"WARC-Payload-Digest\":\"sha1:F2OKTAXQOYTHDF2HI2EUV24EMIFJFJ34\",\"WARC-Block-Digest\":\"sha1:4NRERSCKLFS6HOADLZUG76JFTHXHW524\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2023/CC-MAIN-2023-23/CC-MAIN-2023-23_segments_1685224657169.98_warc_CC-MAIN-20230610095459-20230610125459-00128.warc.gz\"}"}