kotlin - 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)
解决方案
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.
推荐阅读
- sql-server - 一种基于日期计算结果的方法
- mysql - 将 wordpress 数据库迁移到 postgres
- c++ - C++ 中的短消息 AES 性能
- swift - 访问堆栈视图中的标签
- tensorflow - 独特图像上的 YOLO 与 Inception
- java - 活动 JDBC 按字母顺序保存数据
- nem - 错误错误:由于部分为空,完全限定的 id 无效 (:-3087871471161192663)
- c - 重叠 IO 中 WSA_WAIT_EVENT_0 的用途是什么?
- javascript - 如何在 reactjs 中的 props 上使用 reduce()?
- javascript - p5.js 声音:如何使用 removeCue() 删除单个提示