How to properly write class with custom setters and getters?

I tried it like that:

  data class Person() {

        var name: String=""

        fun setName(n: String) {
            name = n

        fun getName():String {
            return name



    fun main(args: Array<String>) {

        val person = Person()

Could you show the closest version to what I’m trying to do ?

Did you mean something like this?

class Person {
	private var _name: String = ""
	var name: String
		get() = _name
		set(value) {
			_name = value
1 Like

It seems, thanks.
My God, what a complicated unintuitive language. Is it really better than Java ?
Hey tieskedh, thank you for not sending me to )

Of course not…
But I expected that it would show a preview…

Of course not…

Why are we here then ? )

I think I shouldn’t answer this, although I don’t know where it went wrong.
I sent a lot of links to this sites and the others all liked the answer.
This means my answer wasn’t the thing being wrong.

Having said that, the way to do it is:

class Person{
    var name : String
    //if you need to overwrite the getter:
     get() = field.capitalize()
     // if you need to overwrite the setter:
     set(value) { field = value.toLowercase() }


And if you have to do the getter/setter over and over, look at delegates

And as a beginner, take a look at:


Thanks a lot.