-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Null Safety
-
Section 4: Object-Oriented Kotlin
-
Section 5: Functional Kotlin
-
Section 6: Coroutines
-
Section 7: Collections Deep Dive
-
Section 8: Type System Deep Dive
-
Section 9: Interop and Tooling
-
Section 10: Kotlin DSLs and Patterns
-
Section 11: Testing and Quality
-
Section 12: Server-Side Kotlin
-
Section 13: Practical Projects
-
Section 14: Interview Practice
-
Section 15: More Practice Exercises
-
Section 16: More Standard Library
-
Section 17: Multiplatform Kotlin
-
Section 18: kotlin.collections In Depth
-
Section 19: kotlin.text In Depth
-
Section 20: kotlin.ranges and kotlin.sequences
-
Section 21: kotlin.io and File Handling
-
Section 22: kotlinx.coroutines Deep Dive
-
Section 23: kotlin.reflect
-
Section 24: Android Development with Kotlin Overview
-
Section 25: Kotlin Multiplatform Deep Dive
-
Section 26: Kotlin for Backend Deep Dive
-
Section 27: Kotlin Design Patterns
-
Section 28: Advanced Language Features
-
Section 29: More Practice Exercises
-
Section 30: More Interview Practice
-
Section 31: Kotlin Type System Deep Dive
-
Section 32: Kotlin Null Safety Advanced
-
Section 33: Kotlin Testing Deep Dive
-
Section 34: Kotlin Build Tooling Deep Dive
-
Section 35: Kotlin Serialization
-
Section 36: Kotlin Performance Considerations
-
Section 37: Kotlin Native Overview
-
Section 38: Kotlin for Data and Scripting
-
Section 39: More Coroutines Practice
-
Section 40: More Android-Adjacent Patterns
-
Section 41: More Practical Projects
-
Section 42: More Design and Architecture Practice
-
Section 43: Kotlin Language Evolution
-
Section 44: More Interview and Review
-
Section 45: Kotlin Delegation Patterns Deep Dive
-
Section 46: Kotlin Annotations Deep Dive
-
Section 47: Kotlin for Gradle Plugin Development
-
Section 48: Kotlin Concurrency Beyond Coroutines
-
Section 49: Kotlin Compiler Internals
-
Section 50: Real-World Kotlin Case Studies
-
Section 51: Final Practice Projects
-
Section 52: Kotlin for Server-Side Reactive Programming
-
Section 53: More Practice and Drills
-
Section 54: Kotlin Security Practices
245: Practice Exercise: Building a Simple Event Sourcing System
How do I actually represent the events so they stay type-safe?
When you're building an event sourcing system, you aren't saving the current state of an object—you're saving the history of what happened to it. In Kotlin, the absolute best way to do this is with a sealed class. Why? Because it forces you to handle every possible event type when you're reconstructing your state, and the compiler will scream at you if you forget one.
Let's use a Digital Wallet as our example. We don't just store the balance; we store every single transaction that ever occurred.
sealed class WalletEvent {
data class AccountOpened(val accountId: String, val owner: String) : WalletEvent()
data class MoneyDeposited(val amount: Double) : WalletEvent()
data class MoneyWithdrawn(val amount: Double) : WalletEvent()
data class AccountClosed(val reason: String) : WalletEvent()
}
By using a sealed class, we've created a closed hierarchy. I've found that this prevents the "mystery event" bug where some developer adds a new event type in a different package and the state-reconstruction logic just silently ignores it.
How do I "replay" these events to get the current state without a mess of if-else blocks?
This is where the magic happens. To get the current state, you take your initial state and "fold" the list of events over it. Think of it like a snowball rolling down a hill; each event adds a layer of data to the state.
I highly recommend creating a separate WalletState data class to hold the current snapshot. Then, use a reduce or fold operation. It keeps the logic clean and functional.
data class WalletState(
val accountId: String = "",
val balance: Double = 0.0,
val isOpen: Boolean = false
)
fun applyEvents(events: List<WalletEvent>): WalletState {
return events.fold(WalletState()) { currentState, event ->
when (event) {
is WalletEvent.AccountOpened -> currentState.copy(
accountId = event.accountId,
isOpen = true
)
is WalletEvent.MoneyDeposited -> currentState.copy(
balance = currentState.balance + event.amount
)
is WalletEvent.MoneyWithdrawn -> currentState.copy(
balance = currentState.balance - event.amount
)
is WalletEvent.AccountClosed -> currentState.copy(
isOpen = false
)
}
}
}
Notice how I used .copy()? Since WalletState is a data class, we treat it as immutable. Never mutate the state directly during a replay; it makes debugging a nightmare when you're trying to trace exactly which event caused a balance to go negative.
Where should the validation logic live? In the event or the aggregate?
This is a common trap. A huge rule of thumb in event sourcing: Events are facts.
An event is something that has already happened. You cannot "validate" a fact. If you have a MoneyWithdrawn event in your store, it means the money was already taken. You shouldn't be checking if the balance is sufficient inside the applyEvents function. If you do that, and your business rules change later, you might find that you can no longer "replay" your old history because the old events now fail the new validation.
Put your validation in a "Command" layer. Check the balance, ensure the account is open, and then emit the event. Once the event is created and saved to the store, the replay logic should be "dumb"—it just applies the change and moves on. This separation is what allows you to change your business rules without corrupting your historical data.
📋 Practical Task
Exercise: Building a Library Book Tracking System
Your goal is to implement a mini event-sourcing system to track the status of a library book. Instead of just marking a book as "checked out," you need to track the entire lifecycle of the book via events.
- Create a sealed class
BookEventwith the following types:BookAdded(containing title and ISBN),BookCheckedOut(containing memberId), andBookReturned. - Create a
BookStatedata class that tracks the title, the ISBN, whether it is currently available, and who currently holds the book (if anyone). - Write a function
reconstructBookState(events: List<BookEvent>): BookStatethat usesfoldto process the events and return the final state of the book. - Test your implementation by creating a list of events (Add -> Checkout -> Return -> Checkout) and verifying that the final state shows the book is checked out to the last member who took it.
There are no comments for now.