delegate method/fields in kotlin

412 Views Asked by At

In java intellij and any other IDE will let you automatically create delegate method to any properties of a class... this helps a lot to speed up the coding process. IS THERE ANY WAY TO DO SOMETHING SIMILAR IN KOTLIN?

why?

i had many fields of a class moved to an inner object now i need to refactor a giant method adding the and extra call to reach these fields... with delegate methods i could solve this in 1 minute on java... how can i do in kotlin?

EXAMPLE

class A(
        var name: String,
        var ref: String,
        var priceCents: Int,
        var maxInstallments: Int = 1,
        ) {

this class became

    class A(
var dto : A_DTO 
            ) {

class A_DTO (
        var name: String,
        var ref: String,
        var priceCents: Int,
        var maxInstallments: Int = 1,
        ) {

so know EVERYWHERE IN MY CODE where i had a.name = "" or something = a.name
i will need to change to a.dto.name = "".... something = a.dto.name

in java this would be a 2 minutes task with no collateral effects how to do in kotlin????

1

There are 1 best solutions below

2
Ricky Mo On

Kotlin has built-in delegation supports. You can use Refractor to extract the interface, then use the by keyword to do the delegation.

interface IA_DTO {
    var name: String
    var ref: String
    var priceCents: Int
    var maxInstallments: Int
}

class A_DTO (
    override var name: String,
    override var ref: String,
    override var priceCents: Int,
    override var maxInstallments: Int = 1,
) : IA_DTO {

}

class A(
    dto : A_DTO
) : IA_DTO by dto
{

}