首页 > 解决方案 > What is the use of "this.toString()" in get()?

问题描述

I found this piece of code in the kotlin docs:

var stringRepresentation: String
get() = this.toString()
set(value) {
    setDataFromString(value) // parses the string and assigns values to other properties
}

I don't understand what this.toString() does here. this refers to the whole object. Why would we want it converted to a string, every time the object is accessed? Should it actually be field.toString()? (but that would be redundant too)

标签: kotlintostringgetter-settergetter

解决方案


It is probably from an imaginary class that can serialize itself into a String by copying its property values to JSON or some other serialized String format. If these properties are mutable, you would want it to generate a new String each time you get the value. And since it has a setter, this imaginary class's setDataFromString function probably takes JSON or some kind of String representation and deserializes it to its own properties.

The getter is only called when stringRepresentation is accessed.

The setter is not using a backing field, so there's no reason for the getter to use the backing field value.


推荐阅读