Skip to content
Tutorials Center
My learning

Topics

Lesson 70 of 134 ยท Idiomatic Kotlin

Operator Conventions

How Kotlin maps symbols like +, [], in, .. and () to functions you can define: plus, get, set, contains, invoke, compareTo, iterator, rangeTo and more, with runnable examples.

When you write a + b in Kotlin, the compiler does not have a special rule for numbers. It looks for a function named plus and calls a.plus(b). The same is true for list[0] (the function get), x in range (contains), for (e in thing) (iterator) and f() (invoke). These fixed pairings of a symbol and a function name are the operator conventions. If your own class has a function with the right name, marked operator, the symbol works on your type too.

The Infix Functions and Operator Overloading lesson introduced the idea with plus. This lesson is the complete map: every family of conventions, how they combine, what the compiler does for you (like turning += into + and an assignment), and the traps that make code surprising. It matters because the standard library itself is built this way: Map, List, String, ranges and Duration all use these functions.

The rule: a name plus the operator modifier

An operator function is an ordinary function (member or extension) with two requirements: the exact name from the table and the operator keyword. Without the keyword the symbol will not compile, which protects you from accidentally giving a symbol to a function that merely has a matching name.

Kotlin A missing 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 says main.kt:6:23: error: 'operator' modifier is required on 'fun plus(other: Vec): Vec' defined in 'Vec'. The fix is a single word: write operator fun plus(...). After that, + works. The message tells you what is missing, not just that something is wrong.

Kotlin Arithmetic operators on your own type

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 next table is the whole list. In every row a is the left operand.

You write The compiler calls
+a, -a, !a a.unaryPlus(), a.unaryMinus(), a.not()
a++, a-- a.inc(), a.dec()
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) (note the swap)
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, -=, *=, /=, %= plusAssign, ... or a = a + b
a == b, a != b a?.equals(b) ?: (b === null)
a < b, <=, >, >= a.compareTo(b) < 0 and so on
for (x in a) a.iterator(), then hasNext() and next() on the result
val (x, y) = a a.component1(), a.component2()
by delegation getValue, setValue, provideDelegate (see Delegation)

Notice %: the function is called rem, not mod. The old mod was deprecated. Also, !=, <, > and the other comparison symbols need no extra function of their own: they are derived from equals and compareTo, so you never write notEquals.

Indexing: get and set

The brackets [] turn into get and set. They can take any number of arguments of any type, which makes them ideal for matrices, grids and lookup objects:

Kotlin get, set and a grid

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.

g[1, 1] = '#' is g.set(1, 1, '#'): the value on the right of = is always the last argument of set. The Map type shows the same idea with its extension operator fun <K, V> MutableMap<K, V>.set(key, value), which is why map["a"] = 1 works.

contains, iterator and ranges

in calls contains on the right operand. An iterator() operator makes a type usable in for, and rangeTo makes .. produce something: usually a ClosedRange. Together they let a custom type take part in the most natural Kotlin syntax. The next example defines a calendar-like Version that is comparable and supports .., in and iteration with step-like behavior.

Kotlin compareTo, rangeTo, contains and iterator

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.

Any type that implements Comparable<T> gets .. for free, because the standard library defines an extension operator fun <T : Comparable<T>> T.rangeTo(that: T). To make a range you can also loop over, your rangeTo must return something that implements Iterable (like IntRange). A plain ClosedRange supports in but not for. Compare Ranges and Progressions.

compareTo can be written as a member of a class that implements Comparable<T> (with override operator) or as a plain extension. The second form lets you add ordering to a type you do not own, but then sorted() and friends will not pick it up, because they require Comparable.

invoke: objects that behave like functions

Defining operator fun invoke(...) lets an instance be called like a function. It is the mechanism behind function types, and it is handy for small "command" objects, validators, or parsers that keep configuration:

Kotlin invoke and a function-like object

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 can also write hello.invoke("x") explicitly. Overloading invoke pays off when an object has a single obvious action; if it has several, give them real names.

Compound assignment: += is not always plus

For a += b the compiler has two possible translations: a = a.plus(b) or a.plusAssign(b). Which one it uses depends on what exists:

  • With only plus, a += b becomes a = a + b, so a must be a var. A val gives an error.
  • With only plusAssign (the "modify in place" form, returning Unit), a += b calls it, and a can be a val, since the variable is not reassigned.
  • With both on your own type, and a a var, the compiler reports an ambiguity (shown below).

This is exactly why the standard collections behave as they do. MutableList has plusAssign; List has only plus:

Kotlin plus versus plusAssign on collections

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 usual rule of thumb is a val for mutable collections and a var for read-only ones, never var plus mutable, which confuses readers (does += modify the object or replace it?). The compiler becomes strict when your own type offers both functions and the variable is a var:

Kotlin plus and plusAssign together (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 cannot choose and reports main.kt:8:7: error: ambiguity between assign operator candidates: followed by the two functions. Change var b to val b and the code compiles and prints [3], because a val cannot be reassigned, so only plusAssign is possible. When you design your own types, offer either plus (immutable) or plusAssign (mutable), not both.

Increment, decrement and equality

inc() and dec() must return the new value; the compiler stores it back into the variable, so the variable must be a var. For a++ the old value is used as the expression result:

Kotlin inc, dec and equals

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.

== calls equals after a null check, so you override equals (and hashCode with it) instead of defining an operator function; there is no operator keyword on equals, it is already declared as one in Any. The chapters Equality and Identity and Object Basics: toString, equals, hashCode cover the contract.

Operators on types you do not own

Extensions can be operators, so you can add symbols to library types. Use that carefully. A good rule: if a teammate seeing a + b would not guess the meaning, use a named function.

Kotlin Extension operators for existing types

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.

Here rangeTo returns a lazy Sequence, not a ClosedRange. That works for for (d in a..b) only if the result has an iterator(), and Sequence does. It also shows the flexibility: rangeTo can return any type.

Rules of good taste

  • Keep the usual meaning. + should be addition or concatenation, [] access, in membership. A Matrix * Matrix is obvious; a User + Order is not.
  • Respect algebra. If a + b is defined, b + a should give a sensible result; if it is not commutative, say so in the docs.
  • Stay immutable by default. Return new objects from plus, times and friends; keep mutation to plusAssign, set and inc.
  • Do not overuse not() and unaryPlus for clever tricks. The builder lesson uses unaryPlus because it is a well-known DSL idiom, not because it is typical.
  • Performance: operators are just calls. a + b + c creates an intermediate object, so for hot loops on big values prefer an in-place operation.
  • Java callers see the function names (plus, get), not the symbols, so a Kotlin operator library is still usable from Java.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the compiler call for x in range?

    The in operator swaps the operands: it is a call of contains on the right-hand object with the left-hand value as the argument.
  2. 2. Why does a[1, 2] = 'x' call a.set(1, 2, 'x')?

    Brackets with an assignment are translated to set(indices..., value). Any number of index arguments is allowed.
  3. 3. A class has both operator fun plus and operator fun plusAssign. What happens with a += b when a is a var?

    With both functions available and a var on the left, either translation is possible, so the compiler rejects the code. Offer only one of the two forms.
  4. 4. Which functions give a class the <, <=, > and >= operators?

    All four comparison operators are derived from a single compareTo call whose result is compared with zero.
  5. 5. What is required for hello("Kotlin") to work on an instance hello of your class?

    Calling an object with parentheses is translated to invoke. The operator modifier is required.

Summary

  • Symbols in Kotlin are shorthand for functions with fixed names: plus, get, set, contains, invoke, compareTo, iterator, rangeTo, inc, and so on.
  • The function must be marked operator; the compiler tells you when the modifier is missing.
  • in calls contains on the right-hand operand; []= calls set with the value last.
  • Comparison operators come from compareTo; == comes from equals.
  • a += b means plusAssign or a = a + b; offering both causes an ambiguity error.
  • Extension operators can add symbols to types you do not own, but keep the meaning obvious.
  • Prefer immutable results for arithmetic operators and a named function when a symbol would surprise people.

Next: Destructuring and Component Functions