CodeGym /Courses /Kotlin SELF /operator in Kotlin: plus, compareTo, plusAssign

operator in Kotlin: plus, compareTo, plusAssign

Kotlin SELF
Level 38, Lesson 2
Available

1. Operator syntax

When you first see that in Kotlin you can write a + b for your own classes, it can feel like the language let you “rewrite math.” In reality, everything is much more down-to-earth (and that’s good): an operator is just a short notation for calling a function with a fixed name. The compiler performs the translation, and after that everything works like regular methods/functions.

The most important convention for today: the expression a + b is translated by the compiler into the call a.plus(b). In other words, an operator is syntactic sugar, not a separate “operator universe.”

Let’s summarize in a small table what we need today (don’t try to memorize it — it’s more important to understand the principle):

What you write What the compiler translates it into
a + b
a.plus(b)
a += b
libo a.plusAssign(b), libo a = a + b (v zavisimosti ot nalichiya plusAssign i vozmozhnosti prisvaivaniya)
a < b
a.compareTo(b) < 0
a > b
a.compareTo(b) > 0

And from this follows a practical conclusion: for your class to “understand” the + operator, you write a regular function plus, but mark it with the operator modifier so the compiler allows operator syntax.

2. plus and +=: surprise-free design

With plus there’s a subtle but very real problem: the + symbol looks harmless, so the reader expects the operation to be fast, predictable, and free of side effects. If inside plus you print to the console, change global state, or delete files (you never know), it’s not the reader’s fault — it’s yours. + should behave “like addition,” otherwise the code turns into a riddle.

Let’s continue developing our educational console application (let’s tentatively call it ExpenseTracker), where we store expenses and build reports. The most common pain point in such programs is money. Storing “money” in Double is like keeping dumplings in your pocket: technically possible, but somehow everything ends up sticky and rounded the wrong way. So let’s introduce a Money type that stores the amount in cents.

Mini model Money and the + operator

@JvmInline
value class Money(val cents: Long)

operator fun Money.plus(other: Money): Money =
    Money(this.cents + other.cents)

fun main() {
    val a = Money(150)
    val b = Money(200)

    println((a + b).cents) // 350
}

Two ideas matter here. First: Money is a “value,” and + creates a new value rather than modifying the old one. Second: + for money reads naturally, without decoding. If a person has to open the implementation to understand the meaning of +, the operator is a poor choice.

There’s a common trap: “what if plus adds to the current object?” That breaks expectations. In most languages and libraries, a + b is understood as creating a result, not mutating a. It’s better to make mutation explicit (a method like add, append, increase) or use plusAssign (+=), where mutation is at least expected from the notation.

If you still do mutation via plus, your code will start behaving like a cat: sometimes affectionate, sometimes it bites, and it’s unclear why.

How += works, and how plusAssign helps

The += operator looks like “addition as well,” but it has a different meaning: it’s augmented assignment. In Kotlin, the compiler tries to call plusAssign, and if it can’t, it turns it into “a = a + b.” This isn’t a guess — it’s a translation rule built into operator conventions.

To avoid confusion, it helps to keep this mini flowchart in mind:

flowchart TD
    A["Code: a += b"] --> B{"Does a.plusAssign(b) exist?"}
    B -- "Yes" --> C["Call a.plusAssign(b) (must return Unit)"]
    B -- "No" --> D["Try a = a + b (i.e., a = a.plus(b))"]

This matters not only “in theory,” but because the behavior of += can depend on whether you have val or var, and whether the object is mutable.

Suppose we don’t have plusAssign, but we do have plus. Then += can become just a convenient notation for “reassignment”:

@JvmInline
value class Money(val cents: Long)

operator fun Money.plus(other: Money): Money =
    Money(this.cents + other.cents)

fun main() {
    var total = Money(0)
    total += Money(99)

    println(total.cents) // 99
}

Why does this work? Because total is a var, so it can be assigned a new value, and total += Money(99) becomes total = total + Money(99).

If there’s no plusAssign and reassignment isn’t possible, the compiler can’t “figure out” what you meant:

@JvmInline
value class Money(val cents: Long)

operator fun Money.plus(other: Money): Money =
    Money(this.cents + other.cents)

fun main() {
    val total = Money(0)
    // total += Money(99) // compilation error: val cannot be reassigned
}

This is where the “fun part” starts, when a beginner says: “wait, but I have val list = mutableListOf(...), and list += x works!” Yes, it works — because MutableCollection has mutating operations, and for mutable collections += can mean changing the contents rather than reassigning the variable. The standard library explicitly describes that plusAssign (+=) exists for collections and, for mutable collections, adds elements “in place.”

The key idea: val forbids changing the reference (the variable), but it does not forbid changing the contents of a mutable object. Therefore:

fun main() {
    val items = mutableListOf("coffee")
    items += "pizza"

    println(items) // [coffee, pizza]
}

This isn’t a violation of the laws of physics — it’s just different levels of mutability: the variable is immutable, the object is mutable.

Your own plusAssign: when it’s appropriate

When you declare operator fun plusAssign(...), you’re essentially promising the reader: “yes, this will mutate the current object.” This is useful for accumulator classes, counters, buffers, reports — anywhere “accumulating” is natural.

The compiler imposes a few strict expectations on plusAssign. One of them is that the return type must be Unit, otherwise you’ll get an error. And that’s logical too: a += b is an assignment, not an expression; no result is expected from it.

Imagine that in ExpenseTracker we have a “category budget” — an object that lives for a long time and changes over time.

@JvmInline
value class Money(val cents: Long)

class Budget(var limit: Money) {
    operator fun plusAssign(delta: Money) {
        limit = limit + delta
    }
}

operator fun Money.plus(other: Money): Money =
    Money(this.cents + other.cents)

fun main() {
    val b = Budget(Money(10_00))
    b += Money(2_50)

    println(b.limit.cents) // 1250
}

Here, mutation is expected: the budget changes. We made plusAssign “boring”: it just updated a field. No prints, no surprises.

In Kotlin, there’s also a rule about ambiguity: if you have both plusAssign and plus, and the left-hand side can be assigned, the compiler may complain about ambiguity in some cases. In practice, this means: don’t try to give + and += two unrelated meanings on the same type if it can confuse both the compiler and people.

A good general rule: + means “produce a new result,” += means “mutate the current accumulator.” If that rule doesn’t hold, it’s worth considering whether a regular method would be better.

3. Comparisons via compareTo

Comparisons are one of the most important reasons to overload operators in business code. When you write if (total > limit), the code reads like natural language. And Kotlin supports this: the operators <, >, <=, >= are translated into calls to compareTo and a comparison with zero.

But it’s easy to make a mistake here that will show up rarely and in the most unpleasant way: implementing compareTo via subtraction.

A correct compareTo for Money

@JvmInline
value class Money(val cents: Long) : Comparable<Money> {
    override operator fun compareTo(other: Money): Int =
        this.cents.compareTo(other.cents)
}

fun main() {
    println(Money(10) < Money(20))   // true
    println(Money(10) > Money(20))   // false
}

We delegated comparison to Long.compareTo, and that’s safe. The meaning of compareTo is simple: positive means “greater,” negative means “less,” zero means “equal.” That’s exactly how Kotlin interprets the result when it rewrites a < b into a.compareTo(b) < 0.

Why you shouldn’t do “return (this.cents - other.cents).toInt()”

Because subtraction can overflow. On small numbers everything will be fine, but on large numbers you can get the wrong sign. The bug will be rare, and that’s exactly why production bug reports love it: they sound like “sometimes the budget is negative, but only on Tuesdays.”

The safe path is to call .compareTo(...).

Comparing by multiple fields and common sense

In ExpenseTracker, expenses may have a date, category, and amount. Let’s imagine a simple expense model (we won’t dive deep into dates; we’ll use a string for the example, because the lecture topic is operators):

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

If we want a “natural order” of expenses by amount, we can create a separate wrapper type or implement Comparable on a different entity. But the main point is that the comparison must be obvious. If you make expenses compare “by title length, then by amount, then by category,” the code user will suffer.

In Kotlin, the standard library explicitly explains that the natural order is defined by Comparable and compareTo — i.e., it’s a contract that sorting relies on. So the “natural order” should truly be natural.

4. Operators in application logic

Now we’ll add operators to bits of logic that actually occur in a console expense-tracking app: accumulating a total, comparing to a limit, and printing a warning. The important thing is that operators here aren’t for aesthetics — they’re for clarity: total + amount and total > limit read better than total.add(amount) or total.isGreaterThan(limit) (although such options are sometimes needed too).

Computing the total amount of expenses

@JvmInline
value class Money(val cents: Long) : Comparable<Money> {
    override operator fun compareTo(other: Money): Int =
        cents.compareTo(other.cents)
}

operator fun Money.plus(other: Money): Money =
    Money(this.cents + other.cents)

fun main() {
    val expenses = listOf(Money(199), Money(350), Money(451))
    var total = Money(0)

    for (x in expenses) total += x
    println(total.cents) // 1000
}

Notice: we used total += x, but Money does not have plusAssign. And that’s fine: here += works as “reassignment via +,” because total is a var.

Checking a limit and printing a warning

@JvmInline
value class Money(val cents: Long) : Comparable<Money> {
    override operator fun compareTo(other: Money): Int =
        cents.compareTo(other.cents)
}

operator fun Money.plus(other: Money): Money =
    Money(this.cents + other.cents)

fun main() {
    val limit = Money(500)
    val spent = Money(650)

    if (spent > limit) {
        println("Warning: you exceeded the limit!") // Warning: you exceeded the limit!
    }
}

The > operator here becomes spent.compareTo(limit) > 0, but you can read the code without knowing this detail — and that’s the main advantage of operators.

5. Operator readability rules

Operators are a very powerful tool, and that’s exactly why it’s easy to ruin them. In good code, an operator is a short, honest notation for an obvious action. In bad code, it’s a puzzle that requires “just in case” comments. Comments are, of course, useful, but it’s better when they aren’t needed to decode +.

A good sanity check is this: imagine your code is being read by someone who knows Kotlin but doesn’t know your project. If they see a + b, they expect “added.” If they see a += b, they expect “added to an accumulator / mutated state.” If they see a < b, they expect “compared by natural order.” If your code does something else, it’s better to choose a named function.

Another practical rule: an operator should be predictably fast. It doesn’t have to be O(1), but it definitely shouldn’t “go to the network and download an exchange-rate feed” (yes, I’ve seen that — and yes, it was painful).

And finally, the most important anti-hero move: don’t use an operator where the meaning isn’t widely understood. Money + Money is fine. User + User is already questionable. Logger + "hello" is suspicious. When in doubt, a named method almost always wins in maintainability.

6. Common mistakes when working with operator, plus, compareTo, plusAssign

Mistake #1: making plus have side effects (printing, changing someone else’s collections, logging “just in case”).
The + symbol looks like a pure “produce a result” operation, and the reader expects the expression can be safely moved, reordered, or extracted into a variable. If plus suddenly prints to the console or mutates state, you’ll get code that “sometimes makes noise” and “sometimes breaks logic” simply because of a refactor.

Mistake #2: implementing compareTo via subtraction.
On small numbers “this.x - other.x” almost always works, so the bug doesn’t show up for a long time. Then overflow happens, the sign becomes wrong, and sorting starts behaving as if the elements’ positions in the queue got shuffled. The safe option is to call .compareTo(...) on the compared field.

Mistake #3: mixing up the meanings of + and += and trying to make them “completely different operations.”
+ usually means creating a new value, while += means mutating an accumulator or reassigning a variable via +. If a + b does one thing, and a += b does something else (unrelated in meaning), the code becomes unpredictable. It’s especially unpleasant if you have both plus and plusAssign, and the compiler starts complaining about ambiguity — that’s a good signal to stop and simplify the design.

Mistake #4: writing plusAssign with a return value (not Unit).
Sometimes you want to “return a new object” and continue chaining. But Kotlin’s += contract expects plusAssign to return Unit, otherwise it’s a compilation error. If you need to “return a result,” you need plus or a regular function with a descriptive name.

Mistake #5: overloading operators for “beauty” and saving keystrokes.
Operators save characters, but can cost hours of reading and maintenance. If, after introducing an operator, the team starts asking “what does + do for this type?”, the operator choice was wrong. In that case, a regular method (for example, addExpense, increaseLimit, mergeWith) often makes the code longer by 5–10 characters, but cheaper by 5–10 nerve cells.

Mistake #6: forgetting that += can mean different things for different types (reassignment or object mutation).
For immutable values, += often becomes a = a + b, which requires var. For mutable collections, += can change the contents even when the variable is a val. If you don’t keep that in mind, you can accidentally write code that looks the same but behaves differently — and then spend a long time explaining to yourself why.

1
Task
Kotlin SELF, level 38, lesson 2
Locked
Player Points
Player Points
1
Task
Kotlin SELF, level 38, lesson 2
Locked
Comparing amounts
Comparing amounts
1
Task
Kotlin SELF, level 38, lesson 2
Locked
Daily step counter
Daily step counter
1
Task
Kotlin SELF, level 38, lesson 2
Locked
Shift temperatures
Shift temperatures
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION