Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delegate method or fields in Kotlin

In Java, IntelliJ and any other IDE will let you automatically create delegate methods 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 extra call to reach these fields... with delegate methods I could solve this in 1 minute in Java... How can I do it 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 I 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 minute task with no collateral effects. How to do the sams in Kotlin ?

like image 519
Rafael Lima Avatar asked Feb 06 '26 07:02

Rafael Lima


1 Answers

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
{

}
like image 128
Ricky Mo Avatar answered Feb 09 '26 09:02

Ricky Mo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!