DEV Community

Cover image for Kotlin delegated properties
Martin Machava
Martin Machava

Posted on

Kotlin delegated properties

Let’s say you have an Entity:

1_WCpNS2pYdSMvro9eOW9xhg

You need to create a DTO for some reason. You probably do it like this:

1_nDGVxuBf6LsAFAaCUOrkXQ

Constructor here serves as a mapper. It maps Entity properties to DTO properties.
Types of DTO properties are resolved from its Entity. That’s good, we do not want to duplicate those types in DTO.
But you can also write DTO with delegated properties:

1_N__7AJ253xNeeDNxsYXG9A

This looks almost the same as the first DTO. So what’s the difference?

  • delegated property is not ”real” property of it’s class
  • instead its getter and setter is delegated to Entity class
  • when Entity property is changed, that change is reflected in DTO delegated property, even when DTO was instantiated before the change
  • when DTO delegated property is changed, the change is reflected in Entity
  • when we do not want to modify delegated property, we set it to val instead of var.

Let’s see it in test example:

1_Kw1Ig7yTktT4OmGFZTGuDw

If you know a good example where to use delegated properties in practice, please, do let me know in the comment.

For more examples, unit tests and integration tests with Hibernate functionality where delegation “extends” the arms of Hibernate’s Entity, see my tests.

Top comments (0)