Introduction In this article, we explore the concept of type classes in Kotlin, a powerful tool that allows developers to abstract logic for different data types. We’ll take data validation as an example to show how type classes can be used to write generic and reusable code. Our implementation will be based on the Arrow Kt library, which will exploit Kotlin’s context receivers. So, without further ado, let’s get the party started. Type classes are tough. If you need to become proficient in Kotlin quickly and with thousands of lines of code and a project under your belt, you’ll love Kotlin Essentials. It’s a jam-packed course on everything you’ll ever need to work with Kotlin for any platform (Android, native, backend, anything), including less-known techniques and language tricks that will make your dev life easier. Check it out here. Setting the Stage We’ll use version 1.9.22 of Kotlin and version 1.2.1 of the Arrow library. We’ll also use Kotlin’s context receivers. Context receivers are still an experimental feature. Hence, they’re not enabled by default. We need to modify the Gradle configuration. Add the kotlinOptions block within the tasks.withType<KotlinCompile> block in your build.gradle.kts file: tasks.withType<KotlinCompile>().configureEach { freeCompilerArgs = freeCompilerArgs + "-Xcontext-receivers" As usual, we’ll put a copy of the configuration file we use at the end of the article. The Problem In this article, we’ll simulate a system for validating user portfolios in a fintech startup, with minimal features. Data validation is crucial in software development, especially in data transactions like user portfolios. Ensuring data conforms to expected formats and rules is vital for maintaining the system’s integrity. So, first, let’s define the data we want to validate. In our case, we want to validate the data contained in some DTOs (Data Transfer Objects). The first DTO represents the creation of a new portfolio: data class CreatePortfolioDTO(val userId...
First seen: 2025-04-17 02:22
Last seen: 2025-04-17 02:22