CodeGym /Courses /Kotlin SELF /Mini API on top of extensions and operators

Mini API on top of extensions and operators

Kotlin SELF
Level 38, Lesson 4
Available

1. Introduction

A mini API is a small set of functions, extensions, and (sometimes) operators that makes code closer to the domain. Not “closer to Kotlin,” not “closer to fashionable DSLs,” but closer to what you actually do: add expenses, compute totals, build a report, format output. It’s a layer that saves repetition and makes main look like a scenario rather than a pile of details.

It’s very easy to confuse a mini API with “let’s build our own programming language in Kotlin.” But the goal is much more modest: so the next person (and you, two weeks later) can open the file and understand what’s going on—without guessing “does the plus operator add numbers or launch a rocket?” So we’ll keep checking ourselves with one question: from a single line of code, is it clear what will happen?

Let’s imagine we’re continuing a training console app for expense tracking (a hypothetical ExpenseTracker). Earlier, we likely had a MutableList<Expense>, commands add/list/remove, and a few reports. Now we want reports to be assembled in a readable and consistent way—and that’s exactly where a mini API fits.

Three rules: “cheap,” “no surprises,” “the name makes the meaning obvious”

Once you start adding extensions and operators, there’s a temptation to “hide” details so deeply that the code becomes pretty but stops being honest. Kotlin conventions provide a guideline: if something looks like a property, it should be cheap and have no surprises; if an action is noticeable, it’s better to make it a function. This rule is especially useful here because a mini API is almost always built out of “small things” that are called often.

Let’s frame the three rules as a behavior checklist:

Tool When it fits Reader expectations Typical “bad surprises”
Extension function fun X.foo() A repeated processing step, formatting, a small business operation This is an action; you can read it as a verb foo does too much, touches I/O, mutates everything in sight
Extension property val X.bar A derived value, a lightweight check It’s “like a field”: fast, stable, with no side effects get() sorts a list, prints to the console, or calls the network
Operator operator fun plus/compareTo/get/set A commonly accepted meaning: addition, comparison, indexing The symbol should read unambiguously + mutates an object, [] means “add if missing,” compareTo compares “however”
infix fun a foo b Rare and targeted: two roles are “almost equal” (like to) It resembles a mini phrase Using it for mutation or where a regular function is clearer

About infix, it’s useful to remember the formal constraints: an infix function must have exactly one parameter, with no vararg and no default value. Infix calls also have their own precedence, so expressions without parentheses sometimes read differently than they execute.

2. Mini model and report

Model: Expense and Money

So the examples aren’t disconnected, let’s agree on small types around which we’ll build the mini API. We’re not diving into architecture and layers—just keeping the code neat and domain-focused.

Let’s start with money. From earlier topics we already know value class, so let the money be in cents to avoid suffering from Double in finance:

@JvmInline
value class Money(val cents: Long)

And an expense:

data class Expense(
    val title: String,
    val amount: Money,
    val category: String
)

For now, the category is a string—intentionally. Yes, we already have enum, but today isn’t about the model; it’s about a mini API on top of output. Categories can be improved separately, and our convenience layer should survive both a string and an enum.

Now let’s decide how we will build a report. The simplest option is to accumulate strings and then joinToString("\n"). But we want adding a line to look the same everywhere and formatting to be consistent. For that, we’ll introduce a small accumulator class Report.

Report as an accumulator: where += fits

The += operator is often perceived as “this is definitely about changing something.” And that’s true: by the operator conventions, a += b turns into a.plusAssign(b) if such a method exists, and the compiler expects a Unit result. That’s a great fit for an accumulator: it exists so you can add to it.

Let’s create a Report that accumulates lines:

class Report {
    private val lines = mutableListOf<String>()

    operator fun plusAssign(line: String) {
        lines.add(line)
    }

    override fun toString(): String = lines.joinToString("\n")
}

A key point here is predictability: Report is a mutable container object. So += really does mean “add inside.” This is similar to how += works for MutableList: for mutable collections it adds elements “in place.”

Let’s test it with a mini example:

fun main() {
    val r = Report()
    r += "TOTAL: 350"
    r += "TOP: food"

    println(r)
    // TOTAL: 350
    // TOP: food
}

If we made it so that r + "..." mutates r, that would be worse: + is usually read as “create a new value” (like List + element, where a new collection is returned). So the rule is simple: mutation means plusAssign or an explicit method; creating a new value means plus.

Extensions for Report: less copy-paste, more consistency

Once Report appears, the next temptation is to write raw strings everywhere: "TOTAL: ${...}", "COUNT: ${...}", and so on. The problem isn’t that it’s hard—it’s that it quickly becomes “everyone does it their own way”: sometimes a colon, sometimes a dash, sometimes extra spaces, sometimes different casing. A mini API exists to make the style consistent and repeatable.

Let’s add an extension function that prints a key–value pair in a single style:

fun Report.kv(key: String, value: Any?) {
    this += "$key: $value"
}

Notice: we deliberately don’t make this infix and we don’t make it an operator. It’s a normal action “add a line,” and the name kv (key-value) is short but still readable in the context of a report.

Usage:

fun main() {
    val r = Report()
    r.kv("TOTAL", 350)
    r.kv("COUNT", 12)

    println(r)
    // TOTAL: 350
    // COUNT: 12
}

Now let’s add a bit more “domain” functionality. For example, money printing: we don’t want to remember cents every time.

fun Money.format(): String = "%.2f".format(cents / 100.0)

And use it in Report:

fun Report.money(key: String, value: Money) {
    this += "$key: ${value.format()}"
}

Now money output is stable, and main doesn’t contain “extra” arithmetic.

3. Formatting and convenient syntax

StringBuilder mini API: chaining without magic

Sometimes it’s more convenient to build a report not via a separate class but directly as a string. Kotlin typically uses StringBuilder and the “build → return the string” approach. For large strings, StringBuilder is more useful than concatenation in a loop, and it’s a good opportunity to build a mini API on top of it.

Let’s make an extension function that appends a line plus a newline and returns this for chaining:

fun StringBuilder.line(text: String): StringBuilder =
    append(text).append('\n')

Now building looks like a “stream of lines”:

fun main() {
    val text = StringBuilder()
        .line("Expense report")
        .line("--------------")
        .line("TOTAL: 350")
        .toString()

    print(text)
    // Expense report
    // --------------
    // TOTAL: 350
}

Why is this a good mini API and not “overkill”? Because the meaning is obvious: line("...") adds a line. There’s no hidden logic, no side effects, no unexpected mutation of something outside StringBuilder. The chain reads left to right like a scenario but remains honest.

Targeted infix: when it’s truly readable

infix looks nice, but it’s tricky because it makes you want to use it “everywhere.” The conventions recommend declaring infix only when both sides are “similar in role,” like to or zip, and avoiding infix for mutation.

Sometimes it’s convenient to write “key–value” pairs, especially if we later want to turn them into a Map. For example, in reports we can first collect the data and then output it.

Let’s create an infix eq that builds a Pair:

infix fun String.eq(value: Any?): Pair<String, Any?> =
    this to value

Usage:

fun main() {
    val p = "TOTAL" eq 350
    println(p) // (TOTAL, 350)
}

Here, infix is justified: the string on the left is the “key,” the value on the right is the “value,” and the roles are fairly symmetric. Plus, it’s not mutation—it’s value creation.

A practical bonus: from an array/list of Pair you can create a Map via toMap(), but it’s important to remember that keys must be unique (the last one overwrites the first).

Mini API for ExpenseTracker: a report from a list of expenses

Now let’s pull everything into a small story: we have a list of expenses, and we want to build a short text report. Not a “mega system,” just a neat function we can call from main.

Let’s create a few small extension functions on the list of expenses. Yes, this is “an API on top of collections,” and Kotlin itself does this extensively: a huge part of the standard library consists of extension functions.

Compute the total across all expenses:

fun List<Expense>.total(): Money {
    var sum = 0L
    for (e in this) sum += e.amount.cents
    return Money(sum)
}

And build a report:

fun List<Expense>.toReport(): Report {
    val r = Report()
    r += "Expense report"
    r.money("TOTAL", this.total())
    r.kv("COUNT", this.size)
    return r
}

Test it:

fun main() {
    val items = listOf(
        Expense("Coffee", Money(350), "food"),
        Expense("Taxi", Money(1200), "transport")
    )

    println(items.toReport())
    // Expense report
    // TOTAL: 15.50
    // COUNT: 2
}

Why is this a good mini API layer?

  • First, main contains almost no details: it says “I have expenses, make a report.”
  • Second, toReport() is a self-explanatory function name, and the name tells you it returns a Report object.
  • Third, the mini API is small: total(), toReport(), Report.kv(), Report.money(), Money.format().

This is not a “universal library of everything,” but targeted conveniences for the task at hand.

4. Risky spots and how to choose a tool

Where a mini API becomes dangerous

Once you get a taste for it, you’ll want to do this: “let’s make any action look like a single button.” And that’s where Kotlin starts testing your maturity as a developer.

For example, it’s a bad idea to make an extension property val List<Expense>.report: String, which internally builds a report, sorts, groups, and formats. It looks like a field, but it does a lot of work. The conventions recommend: a property is appropriate if the computation is cheap, does not throw exceptions, and is stable in its result for the same state. If your report can be expensive, it should be a function (fun buildReport()) so the reader expects “work to be done.”

Another subtle point is collection operators. Many have seen list + element and think it means “add to the list.” But for read-only collections, + returns a new list, and += for a var variable can be reassignment of the result, while for MutableList it can be in-place mutation. This isn’t a problem if you understand it, but in a mini API it’s better not to make the reader guess. That’s why we made Report an accumulator with plusAssign, where the meaning is unambiguous.

And finally, infix. Yes, a foo b looks nice. But infix has precedence, and expressions without parentheses sometimes read differently than they execute. So keep infix for very simple “paired” operations, and everything else as regular functions.

How to choose: extension / operator / infix

To avoid keeping all of this in your head as “fifty rules,” it helps to have a simple mental algorithm. Imagine you want to add a convenience, and ask yourself these questions in this order:

1) Does it look like "reading a property"?
   Yes → make it a val (or extension-val), but only if it's cheap and has no side effects.
   No → keep going.

2) Is it an action with a clear verb?
   Yes → a function (regular or extension).
   No → keep going.

3) Is there a commonly accepted symbol for this (+, [], comparison)?
   Yes → operator, but only if the meaning is unambiguous.
   No → keep going.

4) Are the two sides "almost equal" and will it read like a phrase?
   Yes → infix (rarely and carefully).
   No → a regular function, and don't torture yourself.

This isn’t “Kotlin law,” but a practical habit that saves you from code that looks like magic. And magic in production is bad because it works right up until the first bug—then you suddenly discover that the “magic wand” was actually a double-edged stick.

5. Typical mistakes

Mistake #1: “I’ll make an operator because I can.”
Operators are not for beauty; they’re for predictability. If a + b doesn’t read as “add,” and obj[i] doesn’t read as “get by index/key,” you’re making the code worse. In such places, a regular method (addExpense, appendLine) almost always wins.

Mistake #2: Hiding heavy work inside an extension property.
A property looks like fast data access, so the reader doesn’t expect sorting, grouping, report building, and certainly not exceptions. The conventions recommend using a property only for cheap, stable computations. If the work is noticeable—make it a function.

Mistake #3: Not distinguishing + and += as “new value” vs “mutation.”
In Kotlin, += is compiled by special rules: either plusAssign, or “recreate” via a = a + b. If you overload operators in your own type, keep the semantics crystal clear: plus usually creates a new value, and plusAssign changes an existing one.

Mistake #4: Using infix for mutation or for actions with different roles.
infix looks good where both sides are logically symmetric (like key–value or set union) and looks bad where it’s just a normal command “do this.” The conventions explicitly advise against infix methods that mutate the receiver.

Mistake #5: Inflating a mini API into a “dump of extensions.”
If you put all extensions into one Extensions.kt file with a thousand lines, you’ll get not a mini API but mini chaos. It’s better to keep extensions thematically close to what they serve (for example, ReportExtensions.kt, MoneyFormatting.kt) and avoid creating identical names in different places—otherwise you’ll end up fighting imports later.

Mistake #6: Making a mini API that you can’t “read with your eyes.”
The most unpleasant readability failure is when a line of code stops being self-contained. If, without knowing internal conventions, you can’t tell whether we’re mutating an object or creating a new one, whether the call is expensive, or whether there are side effects—the mini API doesn’t help; it gets in the way. A good convenience layer stays transparent: it reduces noise but doesn’t hide meaning.

1
Task
Kotlin SELF, level 38, lesson 4
Locked
Greeting letter
Greeting letter
1
Task
Kotlin SELF, level 38, lesson 4
Locked
Amount breakdown
Amount breakdown
1
Task
Kotlin SELF, level 38, lesson 4
Locked
User report
User report
1
Task
Kotlin SELF, level 38, lesson 4
Locked
Cell warehouse
Cell warehouse
1
Survey/quiz
Extensions and operators, level 38, lesson 4
Unavailable
Extensions and operators
Extensions and operators
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION