Lenses and Reflection make light work of Kotlin Data Classes

Опубликовано: 26 Март 2026
на канале: Pairing with Duncan
782
46

I seem to be really bad at delivering the episode that I promise the previous week.

Last week (   • Kotlin Data Classes  - Lenses and AI Assis...  ) we looked at data classes and lenses. At the end I said that today we would look at applying lenses to loosely typed property sets, but I’m afraid that you’re going to have to wait.

That’s because I realised that composing lenses is a really interesting topic, and one that makes data class lenses much simpler. I also started playing with reflection and data classes, so that by the end of this episode we have a really nice system to query and update deep trees of immutable data.

In this episode:

00:00:45 Recap
00:01:57 We can navigate easily through data classes
00:02:22 Changing immutable data is hard
00:03:51 Transforming is even worse
00:04:40 Lenses group getting and injector
00:06:53 We can write update in terms of get and inject
00:08:22 Extract a generic lens interface
00:10:13 Implementing an interface with functions
00:13:27 Composing lenses
00:20:10 Check in
00:20:21 Reflection to access copy
00:24:37 Refactor reflectiveCopy to return a function that does the copy
00:27:43 Extract a function to create the lenses
00:27:55 Use the data class property to implement the getter
00:28:36 and generate the injector
00:30:29 One last tidy
00:30:34 IntelliJ paste bug
00:30:59 Review
00:32:17 Plan for next week

You can see a playlist of Data Oriented Programming    • Data Oriented Programming  

If you like this, you’ll probably like my book Java to Kotlin, A Refactoring Guidebook (http://java-to-kotlin.dev). It's about far more than just the syntax differences between the languages - it shows how to upgrade your thinking to a more functional style.