如何在Kotlin中设置属性的值

jaql4c8m  于 2023-02-24  发布在  Kotlin
关注(0)|答案(3)|浏览(256)

我试着设置一个属性值,如下面的代码片段所示。这个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类的值,而不能在第一行设置?

o75abkj4

o75abkj41#

首先,private修饰符是您的问题。
变更

private set(value){field = value}

set(value){field = value}
//public by default

否则你不能在课堂之外使用setter。阅读这里。
对于在类中声明的成员:private表示仅在该类内部可见(包括其所有成员);
其次,你误解了一些东西:

var kon = person.someProperty
 kon = "manulilated"

在这几行中,你并没有改变对象的属性,在创建变量kon之后,作为一个指向somePropertyString,你将这个局部变量重新赋值给其他变量,这个赋值 * 不等于改变 * person.someProperty的值!它对对象完全没有影响。

vc9ivgsu

vc9ivgsu2#

someProperty具有私有setter。当setter为私有时,不能在类外对其进行设置

krcsximq

krcsximq3#

这是一个尝试用Java风格编写Kotlin的好例子。
这是如何在Kotlin促进语言能力。人们可以看到有多少更短和更清楚的代码。个人类只有3行。
使用数据类使我们不必定义hash、equals和toString。

fun test() {
    val person = Person("john", 24)
    var kon = person.someProperty
    person.someProperty = "crap" //this doesn't allow me to set value
    kon = "manulilated"  //this allows me to set the value (yeah, but not in the class, this is a local string)
    val sample_text = SampleText("${person.name}${person.age}")
    sample_text.text = kon

    println("Person = $person")
    println("Kon = $kon")
    println("Sample Text = $sample_text")
}

/** class for person with immutable name and age
 * The original code only has a getter which allows to use 'val'.
 * This can be set in the constructor, so no need for init code. */
data class Person(val name: String, val age: Int) {
    /** The field value is converted to uppercase() (capitalize is deprecated)
    * when the value comes in, so the get operation is much faster which is
    * assumed to happen more often. */
    var someProperty: String = "defaultValue"
        // setter not private as called from outside class
        set(value) { field = value.uppercase() }
}

/** simple class storing a mutable text for whatever reason
 * @param text mutable text
 */
data class SampleText(var text: String) {
    override fun toString(): String {
        return text
    }
}

这就是结果:

Person = Person(name=john, age=24)
Kon = manulilated
Sample Text = manulilated

相关问题