【问题标题】:Kotlin only getter pulblic, private setter [duplicate]Kotlin 仅 getter 公有,私有 setter [重复]
【发布时间】:2018-08-06 12:33:54
【问题描述】:

我刚开始使用 Kotlin,发现 getter 和 setter 非常有用。

我想知道 Kotlin 是否只提供公开的 getter。

它不应该是val,因为它的值可以通过它的类来改变。

我为实现这一目标所做的工作如下。

private var _score: Int=0
val score: Int = _score
   get() = _score

使用这种方式,我必须声明两个变量。

有没有更好的方法只公开 getter?

【问题讨论】:

    标签: kotlin


    【解决方案1】:

    您可以在不定义其主体的情况下定义访问器:

    var score: Int = 0
        private set
    

    在这种情况下,setter 是私有的。

    来自the docs

    如果您需要更改访问器的可见性或对其进行注释, 但不需要更改默认实现,您可以定义 没有定义其主体的访问器:

    var setterVisibility: String = "abc"
        private set // the setter is private and has the default implementation
    

    【讨论】:

      【解决方案2】:

      你可以使用这个语法:

      var setterVisibility: String = "abc" // Initializer required, not a nullable type
          private set // the setter is private and has the default implementation
      

      请参考官方here

      它也是一个带有this question的doublon

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-06-27
        • 2014-07-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-27
        • 1970-01-01
        相关资源
        最近更新 更多