`java.lang.StackOverflowError` when accessing Kotlin property

lee*_*sei 0 kotlin

I got this (contrived) sample from Packt's "Programming Kotlin" on using secondary constructor with inheritance.

Edit: from the answer it is clear that the issue is about backing field. But the book did not introduced that idea, just with the wrong example.

open class Payment(val amount: Int) 

class ChequePayment : Payment { 
    constructor(amount: Int, name: String, bankId: String) :  super(amount) { 
        this.name = name
        this.bankId = bankId 
    }

    var name: String
        get() = this.name
    var bankId: String
        get()  = this.bankId
} 


val c = ChequePayment(3, "me", "ABC")    
println("${c} ${c.amount} ${c.name}")
Run Code Online (Sandbox Code Playgroud)

When I run it this error is shown.

$ kotlinc -script class.kts 2>&1 | more
java.lang.StackOverflowError
    at Class$ChequePayment.getName(class.kts:10)
    at Class$ChequePayment.getName(class.kts:10)
    at Class$ChequePayment.getName(class.kts:10)
Run Code Online (Sandbox Code Playgroud)

Line 10 does seems to be a infinite recursion, how to solve it?

Wil*_*zel 6

You have a recursion in your code:

class ChequePayment : Payment { 
    constructor(amount: Int, name: String, bankId: String) :  super(amount) { 
        this.name = name
        this.bankId = bankId 
    }

    var name: String
        get() = this.name // recursion: will invoke getter of name (itself)
    var bankId: String
        get()  = this.bankId // recursion: will invoke getter of bankId (itself)
} 
Run Code Online (Sandbox Code Playgroud)

If you don't need custom logic for your getter, just leave your properties like this:

var name: String
var bankId: String
Run Code Online (Sandbox Code Playgroud)

They will have a default getter, which does nothing more than returning the value of the backing field.

Note: The code as it is can/should be refactored to this:

class ChequePayment(amount: Int, var name: String, var bankId: String) : Payment(amount) {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

This uses the primary constructor and is much less redundant.