Kotlin has the convenience of custom computed properties in the form of custom getters. Here’s an example computed property from a real app I built which takes properties from a custom Location class and returns a short description of that location.
Kotlin以自定义获取器的形式提供了自定义计算属性的便利。 这是我构建的真实应用程序的示例计算属性,该应用程序从自定义Location类获取属性并返回该位置的简短说明。
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"A custom setter will be called every time a property’s value is set. In my app I need to sometimes save a search result and its type to a Realm database, but I cannot save enum values — only primitive types. So in this case when the enum value of resultType is set, I also set a restultTypeString property for if/when I need to save it in Realm.
每次设置属性值时,都会调用一个自定义设置器。 在我的应用程序中,有时需要将搜索结果及其类型保存到Realm数据库中,但是我无法保存枚举值-仅保存原始类型。 因此,在这种情况下,当设置了resultType的枚举值时,我还将为if /当需要将其保存在Realm中时设置一个restultTypeString属性。
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"To learn more about Kotlin getters and setters, visit the official docs.
要了解有关Kotlin吸气器和吸气器的更多信息, 请访问官方文档 。
翻译自: https://medium.com/swlh/kotlin-property-getters-and-setters-17ffb5a71b98