类成员集(值)递归调用...为什么?

时间:2017-03-04 07:36:44

标签: kotlin

我有一个课程如下

class Employee(var person: String = "Employee", var worksAt: String = "California", var mood: String = "Happy") {
   var name: String = "Name: "
        set(value){
            name = "Name: $value"
        }

    var allString: String
        private set

    init {
        this.allString = "$name works at $worksAt is $mood"
        this.person = "Person: " + person!!
        this.worksAt = "Work at: " + worksAt
        this.mood = "Mood :" + mood
    }

    override fun toString(): String {
        return this.name + "\n" + worksAt + "\n" + mood
    }
}

当我设置名称

        val reaEmployee = Employee()
        reaEmployee.name = edt_main.text.toString()

名称以无限递归方式设置...即获取Name: Name: .... $value ...直到内存不足。我设置错误了什么?

1 个答案:

答案 0 :(得分:7)

这是因为在name的设置器中,您再次设置name,这会调用设置器。

您应该使用field来访问支持字段,而不是调用setter。

field = "Name: $value"