1. Why you need fun interface
When you’re already used to lambdas (like { x -> x > 0 } ) and function types ( (Int) -> Boolean ), it may seem like a separate fun interface construct is “abstraction for the sake of abstraction.” But in practice it solves a very down-to-earth problem: how to name behavior and how to agree on it in an API so that code reads like normal text rather than a pile of parentheses.
Imagine you’re writing an app that has a “command handler,” a “validation rule,” a “formatting strategy,” and so on. Formally, these are all functions. But if you drag types like (AppState, List<String>) -> String everywhere, your brain starts overheating. fun interface lets you say: “this type is a command handler,” and everything becomes clearer right away.
Officially, in Kotlin a functional (SAM) interface is an interface with one abstract method, and Kotlin can “substitute” a lambda as its implementation (SAM conversion).
SAM in plain terms: “one action” as a contract
Let’s translate SAM from spec language into real life. A regular interface often describes “a creature with many responsibilities”: for example, “can draw,” “can save itself,” “can report its name,” “can be closed.” That’s fine.
A SAM interface is an interface about one action, like a button with a single function. For example: “check a number,” “handle an event,” “format a string,” “execute a command.” You need it when you want a named contract (so function signatures read well), but you want to provide the implementation quickly—with a lambda, without the ritual object : ....
In Kotlin, a functional/SAM interface can have any number of non-abstract functions, but the abstract method must be exactly one.
Why not just a function type
At this point a natural question is: “Why introduce fun interface CommandHandler if you can write typealias CommandHandler = (AppState, List<String>) -> String?”
The point is that a functional interface is not the same as a typealias of a function type. An interface defines a named contract and can have additional non-abstract methods, whereas a typealias is just an alias for an existing type.
From a practical perspective, the difference is often this:
| What you choose | When it’s convenient | What you get |
|---|---|---|
| Function type (A) -> B | Internal logic, “passed quickly and forgot about it” | Minimum entities, maximum brevity |
| fun interface | Public API, “this is an important architectural role” | A meaningful type name + the ability to extend the interface with default methods |
So fun interface is a way to make behavior named and domain-specific. When you read CommandHandler, you understand the role. When you read (AppState, List<String>) -> String, you only understand the shape (and even that not always quickly).
2. How to declare fun interface and how SAM conversion works
The key word here is literally fun before interface. This is not “functional interface” in the sense of “somehow related to FP,” but a technical marker: “compiler, please allow SAM conversion and enforce the one-abstract-method rule.”
Minimal example:
fun interface IntPredicate {
fun accept(x: Int): Boolean
}
Here accept is the only abstract method. That’s why Kotlin can do this:
fun interface IntPredicate {
fun accept(x: Int): Boolean
}
fun main() {
val isEven = IntPredicate { x -> x % 2 == 0 }
println(isEven.accept(7)) // false
println(isEven.accept(10)) // true
}
The important idea is: we are creating an interface object, Kotlin just lets us describe it with a single lambda.
What exactly gets “converted” in SAM conversion
When people say “a lambda turns into an interface,” it’s easy to imagine something mystical: like the lambda suddenly becomes a class. In reality, it’s a very straightforward trick: the compiler generates an object that implements the interface, and passes your lambda as the body of the single method.
You can visualize it like this:
flowchart LR
A["Lambda: { x -> x % 2 == 0 }"] --> B["SAM conversion by the compiler"]
B --> C["Object implementing IntPredicate"]
C --> D["accept(x) method calls the lambda"]
So SAM conversion is a way to tell the compiler: “generate an implementation of the interface for me, and here’s the logic.” This is especially handy when you want to store or pass around not “just a function” but an object with a specific contract.
object : ... and a SAM lambda: same meaning, different syntax
The value of SAM conversion usually becomes obvious when you see two snippets side by side: one “like Java in the era of anonymous classes,” the other “like Kotlin.”
The same meaning (evenness check) without SAM conversion:
fun interface IntPredicate {
fun accept(x: Int): Boolean
}
fun main() {
val isEven = object : IntPredicate {
override fun accept(x: Int): Boolean = x % 2 == 0
}
println(isEven.accept(7)) // false
}
And with SAM conversion:
fun interface IntPredicate {
fun accept(x: Int): Boolean
}
fun main() {
val isEven = IntPredicate { it % 2 == 0 }
println(isEven.accept(7)) // false
}
Both variants create an object that can accept. But in the second variant you don’t write extra boilerplate.
3. Example: CLI command handlers with fun interface
Now let’s tie the topic to something more real. Suppose we have a console app for expense tracking (let’s call it BudgetBuddy). Before this, we would most likely write one big when (command) and stuff the logic inside it. It works, but it grows and starts looking like a monolith.
Let’s take a step forward: move the command handlers into a data structure (for example, a Map), but in such a way that a handler is a named contract, not a bare function. fun interface is perfect for this.
Minimal models and the handler contract
First, simple models:
data class Expense(
val id: Int,
val title: String,
val amount: Double
)
class AppState(
val expenses: MutableList<Expense>
)
Now let’s declare the command handler contract:
fun interface CommandHandler {
fun handle(state: AppState, args: List<String>): String
}
Why do we return a String? Because for now we don’t want to complicate the result model. Let the handler simply return the text that main prints. That’s convenient for learning and doesn’t require new entities.
Let’s create a rendering utility:
fun renderExpenses(expenses: List<Expense>): String {
if (expenses.isEmpty()) return "No expenses yet."
return expenses.joinToString(separator = "\n") { e ->
"#${e.id}: ${e.title} — ${e.amount}"
}
}
Now we’ll build a “command registry” using SAM conversion:
fun buildHandlers(): Map<String, CommandHandler> {
return mapOf(
"help" to CommandHandler { _, _ ->
"Commands: help, add, list, exit"
},
"list" to CommandHandler { state, _ ->
renderExpenses(state.expenses)
}
)
}
Notice an important detail: CommandHandler { state, args -> ... } is creating an object for the handler via a lambda.
Calling handlers in main
Now we move to the command-reading loop. We won’t build a big parser; we’ll do a simple version: the command is the first word, and the arguments are the rest.
fun main() {
val state = AppState(mutableListOf())
val handlers = buildHandlers()
while (true) {
print("> ")
val parts = readln().trim().split(" ")
val cmd = parts.firstOrNull()?.lowercase() ?: continue
val args = parts.drop(1)
if (cmd == "exit") break
val handler = handlers[cmd]
val result = handler?.handle(state, args) ?: "Unknown command: $cmd"
println(result)
}
}
The conceptual win here is that main is now responsible for dispatching, not command logic. It reads like “read → find handler → call → print,” and the details live in the handlers.
When “why doesn’t it compile”: the signature must match
When SAM conversion “doesn’t kick in,” the reason is almost always simple: the lambda doesn’t match the abstract method’s parameters or return type.
For example:
fun interface IntTransformer {
fun apply(x: Int): Int
}
The correct version:
val plusOne = IntTransformer { it + 1 }
println(plusOne.apply(10)) // 11
But this won’t work (returns Boolean, but should return Int):
val wrong = IntTransformer { it > 0 } // won't compile
To a beginner this looks like “the compiler is nitpicking.” In reality, it’s saving you from a strange world where the handler “must return an Int,” but you returned “true/false.”
fun interface and closures: convenient, but you can hide state
The trickiest part of lambdas is not the syntax but the fact that a lambda can “capture” external variables. This is called a closure (closures).
Example:
fun interface CounterStep {
fun next(): Int
}
fun main() {
var x = 0
val step = CounterStep {
x += 1
x
}
println(step.next()) // 1
println(step.next()) // 2
}
Technically this works. But architecturally you’ve now created a handler that depends on an external var x. If that handler moves to another file or module, it becomes harder to understand and test: the state is hidden not inside the object but “outside, but nearby.”
Sometimes that’s fine (for example, for a small counter), but in application code it’s useful to keep this rule in mind: if behavior becomes important and long-lived, it’s better for state to be explicit (for example, inside a class/app state structure), rather than accidentally captured.
4. Common mistakes when working with fun interface and SAM conversion
Mistake #1: defining a fun interface with two abstract methods and being surprised that Kotlin complains.
SAM conversion is only possible if there is exactly one abstract method. As soon as you add a second abstract method, the interface stops being functional, and the lambda can no longer unambiguously “become the implementation.” This is not Kotlin being mean; it’s protection against ambiguity.
Mistake #2: mixing up a “functional interface” and a “function type,” and then losing the meaning of the API.
When inside a function you quickly filter a list, (Expense) -> Boolean is great. But if you design a layer with roles like “command handler” or “validator,” a function type turns into eye cryptography. fun interface is exactly what you use so behavior has a name and reads as part of the domain.
Mistake #3: the lambda signature doesn’t match the abstract method, and it seems like SAM doesn’t work.
SAM conversion works when the types match. If a method expects a String and you write a lambda returning an Int, the compiler honestly says: “I can’t substitute this for that.” It often helps to explicitly annotate lambda parameters and see what is expected: { x: Int -> ... } instead of { it -> ... }.
Mistake #4: capturing external var in a lambda and ending up with hidden mutability.
A closure by itself is a normal mechanism. But if you start keeping important application state inside closures, the code becomes difficult to debug: it’s unclear who changes the variable and when. It’s better to keep “official” state in AppState/classes and use lambdas as pure (or almost pure) actions.
Mistake #5: turning a fun interface into a “dump of methods,” losing the “one action” idea.
Yes, a functional interface can have additional methods, but they must be non-abstract. In practice this is a signal: if you started adding lots of logic and different responsibilities, maybe it’s no longer a SAM contract but a regular interface. SAM is good precisely because it’s “single-operation”: one method, one responsibility.
GO TO FULL VERSION