Kotlin-我们如何使用getter和setter访问私有财产?访问方法是在内部调用吗? [英] Kotlin - How can we access private property with getter and setter? Is access methods are calling internally?

查看:100
本文介绍了Kotlin-我们如何使用getter和setter访问私有财产?访问方法是在内部调用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Sample1 {
private var test = ""
    get() = field
    set(value) {
        field = value
   }}

这是我的课程.我想将该属性保留为私有,并且必须通过getter和setter访问该属性.

This is my class. I want to keep the property as private and have to access the property through getter and setter.

 var sample1 = Sample1()

我试图创建一个对象并访问该属性,但是失败了. 当我浏览文档时,我发现了一件有趣的事情, 信件始终具有与该属性相同的可见性". 链接

I tried to create an object and access the property, but fails. When I go through the docs, I could found one interesting thing, "Getters always have the same visibility as the property". link

kotlin的正确方法是什么?

What's the correct approach with kotlin?

推荐答案

科特林将字段,其获取器和设置器(如果适用)分组为属性的单个概念.当访问属性时,总是使用更简单的语法来调用其getter和setter,恰好与访问Java中的字段相同.但是支持该属性的实际字段是私有的,所有调用都通过getter和setter进行,它们与属性本身(在您的情况下为private)具有相同的可见性.所以您的班级会翻译成这样:

Kotlin groups a field, its getter and its setter (if applicable) into the single concept of a property. When you're accessing a property, you're always calling its getter and setter, just with a simpler syntax, which happens to be the same as for accessing fields in Java. But the actual field backing the property is private, and all calls go through the getters and setters, which have the same visibility as the property itself, in your case, private. So your class would translate to this:

public final class Sample1 {

    private String test = "";

    private String getTest() { return test; }

    private void setTest(String test) { this.test = test; }

}

您在Java中对Sample1().text的调用看起来像这样(实际上您可以从调用此Kotlin类的Java代码中执行此操作):

And your call to Sample1().text would look like this in Java (and you can actually do this from Java code that calls this Kotlin class):

new Sample1().getText();

所有要说的是,解决方案是将属性的可见性更改为您在Java中将getter和setter可见性设置为的任何值,例如,更改为默认的公共可见性:

All that to say is that the solution is to change the visibility of the property to whatever you'd set the getter and setter visibilities to in Java, for example, to the default public visibility:

class Sample1 {
    var test = ""
        get() = field
        set(value) {
            field = value
        }
}

请注意,如果没有声明显式的getter和setter,则会自动获得与上述实现相同的功能,因此可以将代码缩短为:

Note that if you don't have an explicit getter and setter declared, you'll get ones automatically which do the same thing as the implementations above, so you can shorten your code to this:

class Sample1 {
    var test = ""
}

此最终代码等效于此Java类:

This final code is equivalent to this Java class:

public final class Sample1 {

    private String test = "";

    public String getTest() { return test; }

    public void setTest(String test) { this.test = test; }

}

这篇关于Kotlin-我们如何使用getter和setter访问私有财产?访问方法是在内部调用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆