英文:
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
我得不到任何值 :(.
所以想知道我做错了什么,以及如何修复它。感谢大家的帮助!
英文:
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<String> = listOf("testing")
var propValue: String = ""
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 -> 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!
答案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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论