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 ?
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
{
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With