Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 134 ยท Functions

Infix Functions and Operator Overloading

Learn Kotlin infix functions and operator overloading - plus, get, invoke, compareTo, contains, unary operators, component functions, rules and mistakes, with runnable examples.

Kotlin lets you write 1 to "one", 0 until 10, list[2], a + b on your own types and if (x in range). None of these are special syntax built into the language for numbers or lists only. They are function calls in disguise. 1 to "one" calls an infix function named to. a + b calls a function named plus. list[2] calls get. Because the rules are open, you can give your own classes the same readable notation.

This lesson covers both features: infix functions, which let you drop the dot and parentheses for one-argument functions, and operator overloading, which maps a fixed set of symbols to functions with fixed names. We also look at the restrictions that keep this power under control, and when you should not use it. You should be comfortable with Functions and Extension Functions first; the follow-up lessons Operator Conventions and Destructuring and Component Functions go deeper.

Infix functions

A function can be called with infix notation (a name b instead of a.name(b)) if it meets three conditions: it is a member or an extension function, it has exactly one parameter (no default value and not a vararg), and it is marked infix.

Kotlin Your first infix function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is ababab, salt & pepper, (1, one), 1, 1 2 3 , 10 downTo 7 step 1 (the progression's own toString) and 20. Many familiar names are infix functions in the standard library: to, until, downTo, step, shl, shr, and, or, xor and zip (as in names zip ages).

An infix call has lower precedence than arithmetic operators and higher than comparison, in, ==, &&. That means 1 + 2 to 3 means (1 + 2) to 3, and a to b == c to d compares two pairs. When in doubt, add parentheses.

A readable mini-DSL

Infix notation is at its best when it makes code read almost like a sentence. A classic use is a tiny testing or validation vocabulary:

Kotlin Infix for a readable check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

You see ok: 4, ok: kotlin is not java, FAIL: expected [1, 2, 3] but was [1, 2] and ok: 5. Real test libraries use the same trick. Do not go overboard: if three infix functions chain in one line, readers cannot see the precedence any more.

What fails

If you forget infix, the compiler tells you:

Kotlin Infix call without the infix modifier (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The message is main.kt:4:15: error: 'infix' modifier is required on 'fun Int.plusTen(x: Int): Int'. Add infix before fun. The modifier is a deliberate opt-in by the function's author; not every function should be callable in this style.

Operator overloading

Kotlin defines a fixed set of operator symbols, each backed by a function with a fixed name. To make + work on your type, declare a function called plus and mark it operator:

Kotlin Overloading plus, minus and unaryMinus

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is $16.49, $8.51, $11.97, -$12.50 and $15.49. a + b is translated to a.plus(b), -a to a.unaryMinus(). Because plus returns a new Money, the result chains naturally. Keep operators pure: they should return a new value and not change the operands.

The operator table

Expression Translated to
+a, -a, !a a.unaryPlus(), a.unaryMinus(), a.not()
a + b, a - b, a * b, a / b, a % b plus, minus, times, div, rem
a..b, a..<b a.rangeTo(b), a.rangeUntil(b)
a in b, a !in b b.contains(a)
a[i], a[i, j] a.get(i), a.get(i, j)
a[i] = v a.set(i, v)
a(), a(x) a.invoke(), a.invoke(x)
a += b a.plusAssign(b) or a = a + b
a++, a-- a.inc(), a.dec()
a == b a?.equals(b) ?: (b === null)
a < b, a >= b a.compareTo(b) < 0, >= 0

The names are fixed. You cannot invent new symbols, and you cannot change precedence. == is special: it always calls equals (which you override, not mark operator); data class writes one for you. The same table, with more detail, is in Operator Conventions.

Missing operator modifier

Kotlin plus without the operator modifier (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler reports main.kt:6:23: error: 'operator' modifier is required on 'fun plus(o: Vec): Vec' defined in 'Vec'. Same idea as infix: the author must opt in.

Indexing, calls and containment

Three more operators make a class feel like a built-in collection or function: get/set for brackets, invoke for call syntax, and contains for in.

Kotlin get, set, invoke and contains

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is 14, true, false and 7. grid[0, 1] = 5 calls set(0, 1, 5) (the last argument is the assigned value). grid(7) calls invoke(7), which lets objects behave like functions. That is how function types work internally and how a class can act as a callable "command" or "use case".

Comparison with compareTo

If your class implements Comparable, you get <, >, <=, >= for free, because they translate to compareTo. Here compareTo is already operator in the interface, so you do not repeat the keyword:

Kotlin compareTo and comparison operators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

You get true, false, 2.0, [1.9, 1.10, 2.0] and true. Once a type is Comparable, a..b creates a range (via the library's rangeTo extension for comparables) and in works with it. See Sorting and Comparators for more on ordering.

Assignment operators and increment

a += b has two possible meanings. If plusAssign exists, it is called (usually to mutate a mutable collection). Otherwise Kotlin rewrites to a = a + b, which needs plus and a var. If both are applicable, the compiler reports an ambiguity:

Kotlin plus versus plusAssign

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is [apple, pear], [1, 2, 3] and [1, 2]. This also explains an everyday puzzle: val numbers = mutableListOf(1); numbers += 2 mutates the list through plusAssign, while var numbers = listOf(1); numbers += 2 builds a new list through plus and reassigns the variable.

Guidelines

  • Keep the meaning obvious. + on Money, Vector or Duration is natural; + on User is not. If a reader cannot guess what the operator does, use a named function.
  • Overloads should behave like the originals. plus should be symmetric where it makes sense, compareTo should be consistent with equals, and get should not have surprising side effects.
  • Prefer extensions for types you do not own. operator fun Pair<Int, Int>.plus(other: Pair<Int, Int>) works but can confuse people who do not know it exists. Keep such operators close to where they are used.
  • Infix for sentence-like code only, with one clear argument. Do not make every two-argument function infix.
  • Remember operator and infix are opt-in. Third-party and Java code can be called with infix or operator syntax only where the author (or a Kotlin-aware convention) allows it. Java methods named like operators (get, plus, compareTo) are automatically usable as operators.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which conditions must a function meet to be called with infix notation?

    An infix function must be a member or extension, take a single parameter (no default, no vararg) and carry the infix modifier.
  2. 2. What does a[1] = 5 translate to?

    Bracket assignment calls set with the indices followed by the assigned value.
  3. 3. Which function name does the expression x in y call?

    in is translated to y.contains(x), so the container is the receiver.
  4. 4. You declare fun plus(other: Vec): Vec in a class without the operator keyword. What happens at v1 + v2?

    Operator functions must be marked operator explicitly; otherwise the compiler rejects the operator syntax.
  5. 5. Given var list = listOf(1, 2), what does list += 3 do?

    A read-only List has no plusAssign, so the compiler uses list = list + 3, which needs a var.

Summary

  • An infix member or extension with one parameter can be called as a name b; the standard library uses this for to, until, downTo, step, shl, and and more.
  • Operators map to functions with fixed names (plus, get, invoke, compareTo, contains...) that you mark operator.
  • Both infix and operator are opt-in; forgetting them gives a clear compile error.
  • += uses plusAssign if available, otherwise plus plus reassignment of a var.
  • Implementing Comparable gives you <, >, <=, >= and ranges.
  • Use these tools when the notation is natural for the type, and use plain function names otherwise.

Next: Recursion and tailrec