Reputation: 9
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
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
Reputation: 171
fun main(){
val car=Car()
print(car.myCar)
}
class Car {
var myCar: String="BMW"
get() = field
}
Upvotes: 0