user5539487
user5539487

Reputation:

Kotlin - Understanding Getters and Setters

Kotlin auto-generates it's getters and settings, but I never refer to them? Also, what is the correct way to write a custom getter/setter in Kotlin? When I say myObj.myVar = 99 I feel like myVar is a public field of myObj that I'm accessing directly? What is actually happening here?

Upvotes: 14

Views: 11071

Answers (2)

Ricky Padilla
Ricky Padilla

Reputation: 256

Here are some real world examples of custom getters and setters. You can see more here.

// Custom getter example
val friendlyDescription get(): String {
    val isNeighborhood = district != null
    var description = if (isNeighborhood) "Neighborhood" else "City"
    description += " in"
    if (isNeighborhood) {
        description += " $city,"
    }
    province?.let {
        if (it.isNotEmpty()) {
            description += " $it,"
        }
    }
    description += " $country"
    return description
}

print(myLocation.friendlyDescription) // "Neighborhood in Denver, Colorado, United States"

// Custom setter example
enum class SearchResultType {
    HISTORY, SAVED, BASIC
}

private lateinit var resultTypeString: String

var resultType: SearchResultType
    get() {
        return enumValueOf(resultTypeString)
    }
    set(value) {
        resultTypeString = value.toString()
    }

result.resultType = SearchResultType.HISTORY
print(result.resultTypeString) // "HISTORY"

Upvotes: 0

user5539487
user5539487

Reputation:

This has been answered in a few places, but I thought that I would share a concrete example for people transitioning to Kotlin from Java/C#/C/C++, and who had the same question that I did:

I was having difficulty in understanding how getters and setters worked in Kotlin, especially as they were never explicitly called (as they are in Java). Because of this, I was feeling uncomfortable, as it looked like we were just directly referring to the vars/vals as fields. So I set out a little experiment to demonstrate that this is not the case, and that in fact it is the implicit (auto-generated) or explicit getter/setter that is called in Kotlin when you access a variable/value. The difference is, you don't explicitly ask for the default getter/setter.

From the documentation - the full syntax for declaring a property is:

var <propertyName>: <PropertyType> [= <property_initializer>]
   [<getter>]
   [<setter>]

And my example is

class modifiersEg {

/** this will not compile unless:
 *      - we assign a default here
 *      - init it in the (or all, if multiple) constructor
 *      - insert the lateinit keyword    */
var someNum: Int?
var someStr0: String = "hello"
var someStr1: String = "hello"
    get() = field  // field is actually this.someStr1, and 'this' is your class/obj instance
    set(value) { field = value }

// kotlin actually creates the same setters and getters for someStr0
// as we explicitly created for someStr1

var someStr2: String? = "inital val"
    set(value) { field = "ignore you" }

var someStr3: String = "inital val"
    get() = "you'll never know what this var actually contains"

init {
    someNum = 0

    println(someStr2) // should print "inital val"

    someStr2 = "blah blah blah"
    println(someStr2) // should print "ignore you"

    println(someStr3) // should print "you'll never know what this var actually contains"
}

I hope that helps to bring it all together for some others?

Upvotes: 23

Related Questions