Kotlin – 构造函数中初始化属性的设置器?

huangapple go评论47阅读模式
英文:

Kotlin - Setter for Properties Initialized in Constructor?

问题

希望我表达得对。尝试为在构造函数中初始化的变量创建一个设置函数,示例如下:

package com.example.propory

class Property(val name: String, propValue: String) {

    var previousPropertyValue: List<String> = listOf("testing")

    var propValue: String = ""
        set(value) {
            previousPropertyValue += this.propValue
            field = value
        }
}

当我创建它的实例时,我可以很好地访问"name",如下所示:

// 省略部分
val currentProperty = Properties.find { prop -> property.name == prop.name}

然而,如果我尝试访问"propValue":

currentProperty.propValue = property.propValue

我得不到任何值 :(.

所以想知道我做错了什么,以及如何修复它。感谢大家的帮助! Kotlin – 构造函数中初始化属性的设置器?

英文:

hope I worded this right. Trying to be able to do a setter function for a variable that is initialized in a constructor ala:

package com.example.propory

class Property(val name: String, propValue: String) {

    var previousPropertyValue: List&lt;String&gt; = listOf(&quot;testing&quot;)

    var propValue: String = &quot;&quot;
        set(value){
            previousPropertyValue += this.propValue
            field = value
        }
}

I can access "name" just fine outside of this when I create a instance of it ala:

// trunicated
 val currentProperty = Properties.find { prop -&gt; property.name == prop.name}

however if I try to access "propValue":

currentProperty.propValue = property.propValue

I don't get any value :(.

So wondering what I did wrong and how to fix it. Thank you all for the help! Kotlin – 构造函数中初始化属性的设置器?

答案1

得分: 1

您完全没有使用传递给构造函数的 propValue 参数,并用空字符串初始化属性。请使用传递给构造函数的参数来进行初始化:

var propValue: String = propValue
    set(value){
        previousPropertyValue += this.propValue
        field = value
    }
英文:

You're leaving the propValue parameter that is passed into the constructor completely unused, and initializing your property with an empty String. Initialize it with the parameter that was passed into the constructor:

var propValue: String = propValue
    set(value){
        previousPropertyValue += this.propValue
        field = value
    }

huangapple
  • 本文由 发表于 2023年3月3日 23:33:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/75629047.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定