Kotlin 中的 Getter 和 Setter

编程入门 行业动态 更新时间:2024-10-24 11:17:57
本文介绍了Kotlin 中的 Getter 和 Setter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

例如,在 Java 中,我可以自己编写 getter(由 IDE 生成)或在 lombok 中使用诸如 @Getter 之类的注解——这非常简单.

In Java, for example, I can write getters on my own (generated by IDE) or use Annotations like @Getter in lombok - which was pretty simple.

Kotlin 具有默认情况下的getter 和setter.但我不明白如何使用它们.

Kotlin however has getters and setters by default. But I can't understand how to use them.

我想实现,比如说 - 类似于 Java:

I want to make it, lets say - similar to Java:

private val isEmpty: String get() = this.toString() //making this thing public rises an error: Getter visibility must be the same as property visibility.

那么getter是如何工作的呢?

So how do getters work?

推荐答案

Getter 和 setter 在 Kotlin 中自动生成.如果你写:

Getters and setters are auto-generated in Kotlin. If you write:

val isEmpty: Boolean

相当于下面的Java代码:

It is equal to the following Java code:

private final Boolean isEmpty; public Boolean isEmpty() { return isEmpty; }

在您的情况下,私有访问修饰符是多余的 - isEmpty 默认是私有的,只能由 getter 访问.当您尝试获取对象的 isEmpty 属性时,您实际上会调用 get 方法.为了更深入地了解 Kotlin 中的 getter/setter:下面的两个代码示例是相等的:

In your case the private access modifier is redundant - isEmpty is private by default and can be accessed only by a getter. When you try to get your object's isEmpty property you call the get method in real. For more understanding of getters/setters in Kotlin: the two code samples below are equal:

var someProperty: String = "defaultValue"

var someProperty: String = "defaultValue" get() = field set(value) { field = value }

我还想指出,getter 中的 this 不是您的财产 - 它是类实例.如果你想在 getter 或 setter 中访问字段的值,你可以使用保留字 field :

Also I want to point out that this in a getter is not your property - it's the class instance. If you want to get access to the field's value in a getter or setter you can use the reserved word field for it:

val isEmpty: Boolean get() = field

如果您只想在公共访问中使用 get 方法 - 您可以编写以下代码:

If you only want to have a get method in public access - you can write this code:

var isEmpty: Boolean private set

由于靠近 set 访问器的 private 修饰符,您只能在对象内部的方法中设置此值.

due to the private modifier near the set accessor you can set this value only in methods inside your object.

更多推荐

Kotlin 中的 Getter 和 Setter

本文发布于:2023-05-27 09:57:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/285771.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:词库加载错误:Could not find file 'D:\淘小白 高铁采集器win10\Configuration\Dict_Sto

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!