1. Introduction
If you’re just getting started, the idea “let’s make an event instead of calling it directly” may feel like overengineering. And sometimes that’s true: if you have one handler and it’s always the only one, it’s simpler to call it directly. But as soon as you get several independent reactions to a single action, direct calls turn the code into a combine harvester: you add a println, then “one more println,” then “one more function,” and suddenly you have a 200-line method that both “does the job” and “reacts to the job.”
An event helps separate roles. The source says: “I added an expense.” And listeners decide what to do: log it, update the UI, compute statistics, send a notification. The source does not have to know who those listeners are. Our goal today is to implement the simplest mechanism: “the source stores a list of functions and calls them.”
Who is a listener in Kotlin: function type (T) -> Unit
Before writing Event<T>, you need a very down-to-earth understanding of what exactly we’re going to store in the list. We will store functions. Yes—just like numbers, strings, and lists, only functions.
Kotlin has function types for this, for example (Int) -> String or (ExpenseAdded) -> Unit. This type reads almost like a regular function signature: “takes T, returns Unit.” Kotlin directly uses this notation for variables, parameters, and collections of functions.
Here is the smallest example of a “listener” without events—just a function stored in a variable:
fun main() {
val listener: (String) -> Unit = { s ->
println("Got message: $s")
}
listener("Hello!") // Got message: Hello!
}
Notice two things. First, the lambda has a parameter s, and it’s a regular variable. Second, the return value is Unit, meaning “we don’t return anything useful, we just perform an action.”
This is the ideal shape for an event handler: the event “delivered data,” the handler “did something.”
2. Minimal contract for Event<T>
When we say “let’s make a class Event<T>,” it’s important not to slip into “now we’ll build our own Spring inside a console project.” Today we’re doing the minimum, but in a way that the minimum is neat and ready to extend (when the time comes).
Let’s formulate the contract in plain language. Our Event<T> must:
- store a list of listeners (functions of type (T) -> Unit);
- allow subscribing: subscribe(listener);
- allow publishing an event: emit(value)—and call all listeners one by one;
- be type-safe: if the event is Event<ExpenseAdded>, then the listener must accept ExpenseAdded, not “anything.”
And one more important point: the listeners list must be hidden inside. From the outside, there should be no way to do “oops, I accidentally cleared listeners.” So we make the list private.
4. Implementing Event<T>: a MutableList of listeners
Now let’s write the class itself. We’ll create a private field listeners and store lambdas there.
This is where you can clearly see why we needed collections and function types earlier: listeners is literally a MutableList<(T) -> Unit>.
class Event<T> {
private val listeners = mutableListOf<(T) -> Unit>()
fun subscribe(listener: (T) -> Unit) {
listeners += listener
}
fun emit(value: T) {
for (l in listeners) l(value)
}
}
A lot of meaning is packed into these three lines:
In listeners += listener we use the += operator, which for a MutableList adds an element “in place” (this is plusAssign). It’s just a shorter form of listeners.add(listener).
In emit we loop through the list and call each handler: l(value). It looks like a “function call” because l is a variable of a function type, so you can call it like a regular function.
If there are no subscribers, the loop simply doesn’t run. That’s a normal contract: the event “silently passes.”
5. Event data: why the type T is needed
The type parameter T is what makes our Event truly convenient. It fixes what data the event carries.
You could make a “universal” event on Any and pass anything there, but then you immediately lose half of Kotlin’s value: the compiler would stop protecting you from mistakes.
In Kotlin, the idea “a function type includes the parameter type” is fundamental. If you have val f: (Int) -> Unit, you can’t accidentally pass a string to it. Same here: if the event is Event<ExpenseAdded>, the listener must accept ExpenseAdded. That is “type safety.”
By the way, Kotlin documentation describes this as “function types”: the notation (A, B) -> C corresponds to functions that accept arguments of types A, B and return C.
6. Example: the “expense added” event
So the example isn’t in a vacuum, let’s continue our training console app (let’s call it BudgetBook): we add expenses and want to react to the fact that an expense was added.
Let’s make a simple payload type. In a real project this might be your data class Expense(...), but to keep the example compact, we’ll take a separate “event wrapper.”
data class ExpenseAdded(val title: String, val amount: Int)
Now let’s make a service that adds an expense (for now it just prints) and emits an event:
class ExpenseService {
val expenseAdded = Event<ExpenseAdded>()
fun addExpense(title: String, amount: Int) {
println("Added expense: $title ($amount)")
expenseAdded.emit(ExpenseAdded(title, amount))
}
}
Notice a subtle architecture point. ExpenseService does not do “logging,” “UI,” or “statistics.” It does its job and reports the fact: “expense added.” Everything else is up to subscribers.
7. Subscribers: many reactions to one event
Now let’s show that an event is a “1 → many” model. One source, many listeners—and they don’t have to know about each other.
fun main() {
val service = ExpenseService()
service.expenseAdded.subscribe { e -> println("Audit: ${e.title}") }
service.expenseAdded.subscribe { e -> println("UI: +${e.amount}") }
service.addExpense("Coffee", 5)
// Added expense: Coffee (5)
// Audit: Coffee
// UI: +5
}
The nice part is that addExpense doesn’t change when we add new reactions. Want a third reaction? Just add one more subscribe.
Another useful trick is to pull the lambda into a variable so it gets a name. This makes the code feel less “magical”:
fun main() {
val service = ExpenseService()
val statsListener: (ExpenseAdded) -> Unit = { e ->
println("Stats: amount=${e.amount}")
}
service.expenseAdded.subscribe(statsListener)
service.addExpense("Sandwich", 7)
// Added expense: Sandwich (7)
// Stats: amount=7
}
8. Limitations of the minimal version and the interaction diagram
It’s important to be honest: this version of Event<T> is minimal. It solves the main problem: “store a list of handlers and call them.” But it contains several deliberate simplifications.
First, we don’t solve “how to unsubscribe.” For now, a subscription is “forever” (for the lifetime of the Event object). This is not a bug—just an uncovered topic: we intentionally don’t complicate the interface today so you can feel the basic mechanics.
Second, we don’t implement any protection against a handler throwing an exception. Right now, if one listener crashes, the execution of emit will stop on it, and the remaining listeners may not run. In some scenarios this is even desirable (the error is critical), but more often you want one failing handler not to break the whole dispatch. However, that’s already a “dispatch reliability” topic, and we won’t implement it today so we don’t mix two topics into one mess.
Third, we don’t discuss “dangerous” cases where a handler modifies the listeners list during dispatch. That’s a separate engineering story: it’s important, but for a minimal event it’s too early.
Our goal today is for you to clearly understand: Event<T> is just a small object with a MutableList of functions and two methods.
A small diagram: who talks to whom
Sometimes it’s more useful to see the architecture than to read yet another paragraph. In minimal form it looks like this:
flowchart LR
S["ExpenseService
(fact source)"] -->|"emit(ExpenseAdded)"| E["Event⟨ExpenseAdded⟩"]
E --> L1["Audit listener
(log/audit)"]
E --> L2["UI listener
(message to the user)"]
E --> L3["Stats listener
(statistics)"]
And notice: there are no arrows “listener → service” here. The service doesn’t have to know subscribers exist at all. That’s exactly what gives you loose coupling: the source reports a fact, and reactions are connected from the outside.
9. Common mistakes
Error #1: making the listeners list public “because it’s convenient.”
Almost always this ends with someone outside doing event.listeners.clear() or adding something in a way you didn’t expect. As a result, the event starts behaving unpredictably, and you catch bugs like “why are my handlers sometimes not called.” The list must be private, and only the subscribe and emit methods should be exposed.
Error #2: storing listeners as Any (or () -> Unit for all cases).
It seems like “more universal” means “better.” In practice, you lose type safety and start dragging in casts, type checks, and other pain from the world of dynamic languages. Kotlin’s strength is that (T) -> Unit fixes the handler contract, and Event<T> fixes the event contract. Function types are a normal and supported language feature.
Error #3: confusing an “event” with a “command.”
If you name an event sendEmailEvent, you subconsciously turn it into the command “send an email.” This makes the architecture worse: the source starts thinking about a specific reaction. It’s better to name an event as a fact: userSaved, expenseAdded, reportGenerated. Then any handler can decide what to do with that fact: send an email, write a log, compute statistics, etc.
Error #4: expecting emit to “return something” that you can rely on.
In our model, listeners return Unit, and emit also returns nothing. This is intentional design: an event is broadcasting a fact, not computing a result. If you need to collect results from multiple handlers and aggregate them—that’s a different contract and a different task. If you try to cram that into Event<T> right away, you’ll get an inconvenient monster.
Error #5: adding extra business logic into Event.
Sometimes you want Event.emit to print println("Event happened!") itself. It feels convenient, but quickly turns Event into a place that “knows too much.” Event should be infrastructure: store subscribers and call them. If you need logging—subscribe a separate listener (and that’s actually a great demonstration that events work).
GO TO FULL VERSION