Getters and setters in Kotlin: how to declare and use properties with custom accessors?
Hi everyone! I recently started learning Kotlin after Java and encountered a misunderstanding of how getters and setters work. In Java, I'm used to explicitly declaring fields with access modifiers and then writing getField() and setField() methods for them. In Kotlin, as I understand, everything is different — there are properties that automatically generate getters and setters.
// Example from my attempt\nclass Person {\n var name: String = "Unknown"\n var age: Int = 0\n \n // I'm trying to make a custom setter for age\n set(value) {\n if (value >= 0) {\n // How do I access the field here? field? Or this.age?\n this.age = value // Causes recursion!\n } else {\n println("Age cannot be negative")\n }\n No answers yet.
Log in to leave an answer