Aditya Dixit
Aditya Dixit

Reputation: 9

Error while using getters and setters in kotlin

I was trying to write a getter in kotlin. Here is my code:

fun main(){
    val car=Car()
    print(car.myCar)
}

class Car {
    var myCar: String="BMW"
    get() {
        return this.myCar.toLowerCase()
    }
}

When I executed I got this exception: Exception in thread "main" java.lang.StackOverflowError

I saw in some tutorial where they use field.

My question is why this is giving me an exception and why and how should I use field

Upvotes: 0

Views: 454

Answers (2)

Sinner of the System
Sinner of the System

Reputation: 2966

you created an infinite loop.

var myCar: String = "BMW"
    get() {
        return this.myCar.toLowerCase()
    }

is equal to

var myCar: String = "BMW"
    get() = this.myCar.get().toLowerCase()

as you can see, your "get" function is recursive. So you need to use the field keyword to avoid calling the get() method:

var myCar: String = "BMW"
    get() = field.toLowerCase()

Upvotes: 3

damir huselja
damir huselja

Reputation: 171

fun main(){
    val car=Car()
    print(car.myCar)
}

class Car {
    var myCar: String="BMW"
    get() = field
}

Upvotes: 0

Related Questions