【发布时间】:2017-12-28 21:49:44
【问题描述】:
我试图设置一个属性值,如下面的 sn-p 所示。这个SO question 没有回答这个问题。
var person = Person("john", 24)
//sample_text.text = person.getName() + person.getAge()
var kon = person.someProperty
person.someProperty = "crap" //this doesn't allow me to set value
kon = "manulilated" //this allows me to set the value
sample_text.text = kon
class Person(val n: String, val a: Int){
var pname: String = n
var page: Int = a
var someProperty: String = "defaultValue"
get() = field.capitalize()
private set(value){field = value}
fun Init(nm: String, ag: Int){
pname = nm
page = ag
}
fun getAge(): Int{
return page
}
fun getName(): String{
return pname
}
}
为什么我可以在第二行设置 Person 类的值,但不能在第一行设置?
【问题讨论】:
-
顺便说一句,提供
getAge()和getName()函数绝对没有意义 - kotlin 自动为所有变量创建 getter(除了那些用@JvmField注释的变量)