DEV Community

Cover image for Kotlin delegated properties
Martin Machava
Martin Machava

Posted on

1

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.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay