Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 134 ยท Getting Started

Operators

Learn Kotlin operators - arithmetic, comparison, logical, assignment, increment, bitwise functions like shl and and, the in and is operators, precedence rules and a preview of operator overloading.

An operator is a symbol that combines or tests values: +, ==, &&, in. You have already used several. Kotlin's operator set is familiar if you know Java or C, with a few deliberate differences: == compares content, bitwise operations are named functions instead of symbols, there is no ternary ?: (the if expression replaces it), and every operator is secretly a function call, which is what makes operator overloading possible.

This lesson goes through the groups of operators, shows the places where behavior differs from other languages, and ends with the precedence table and a preview of overloading. Types such as Int and Double are covered in Basic Types and Working with Numbers.

Arithmetic

The basic five are +, -, *, / and % (remainder). The result type follows the operands: two Ints give an Int, and mixing with a Double gives a Double.

Kotlin Arithmetic and integer division

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.

Integer division is the number one source of "why is my average wrong" bugs: 7 / 2 is 3, not 3.5, and -7 / 2 is -3 (it truncates toward zero, it does not round down). When you need the exact quotient, make one side a Double, as in 7 / 2.0, or convert with toDouble(). The % operator keeps the sign of the left operand; mod() gives the mathematical modulus, which is non-negative for a positive divisor and therefore safer for wrapping indexes around.

Dividing an Int by zero is a run-time failure, unlike floating point:

Kotlin Integer division by zero (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 first line prints Infinity. The second stops the program with java.lang.ArithmeticException: / by zero.

Comparison and equality

<, >, <=, >= compare ordered values, == and != test equality. As you saw in Strings, == calls equals(): it compares content. === and !== test whether two references are the very same object.

Kotlin Comparison, equality and identity

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 last two lines carry a lesson that applies to every language: 0.1 + 0.2 is 0.30000000000000004, so comparing Double values with == is a trap. Compare with a small tolerance, or use BigDecimal for exact decimal values.

You can also use compareTo directly. A comparison like a < b is turned into a.compareTo(b) < 0 by the compiler, which means any class that has a compareTo function can use these operators (see the overloading section).

Logical operators

&& (and), || (or) and ! (not) work on Boolean values. && and || are short-circuiting: the right side is evaluated only if it can still change the result. This is not only an optimization, it is how you write safe checks:

Kotlin Short-circuit evaluation

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 infix functions and, or and xor on Boolean exist too, but they always evaluate both sides. Use && and || almost always.

Assignment and increment

= assigns. The compound forms +=, -=, *=, /=, %= combine an operation with an assignment. ++ and -- add or subtract one, and they exist in prefix and postfix form, just as in Java:

Kotlin Compound assignment and ++

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.

Assignment in Kotlin is a statement, not an expression: you cannot write while ((line = readLine()) != null) as in C or Java. That removes a family of bugs (if (x = 5) is a compile error) at the cost of a slightly different style, shown in Reading Input.

There is a subtle rule for +=. On a var of an immutable type (like a read-only List), list += item means list = list + item, creating a new list. On a val holding a mutable list it calls plusAssign, which changes the list in place. If both are possible, the compiler reports ambiguity, so you pick val for the mutable list or var for the immutable one.

Bitwise operations are functions

Kotlin has no &, |, ^, <<, >>, ~ symbols. Instead the integer types have infix functions with names:

Function Meaning C/Java equivalent
a and b bitwise AND a & b
a or b bitwise OR a | b
a xor b bitwise XOR a ^ b
a.inv() flip all bits ~a
a shl n shift left a << n
a shr n arithmetic shift right (keeps sign) a >> n
a ushr n logical shift right (fills with zeros) a >>> n
Kotlin Bitwise functions

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.

Both checks print true. The first, perms and write != 0, works because named infix functions like and bind tighter than !=, so Kotlin reads it as (perms and write) != 0. In C or Java the equivalent perms & write != 0 is a famous trap, because != binds tighter there. The safe habit is still to add parentheses, as in the second line, so readers do not need the precedence table. Bits and masks get their full treatment in Bits and Bytes.

in, !in, is, !is and the range operator

Some operators are keywords. in tests membership in a range, collection or string. is tests a type (see Type Checks and Casts). .. creates a range:

Kotlin in, is and ranges

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.

score in 60..79 replaces the clumsy score >= 60 && score <= 79. The ?. and ?: operators deal with nulls and get their full treatment in Null Safety. The double-bang !! also exists, and mostly signals a bug waiting to happen.

Precedence, from highest to lowest

When an expression has several operators, the higher ones bind first. You rarely need to memorize the table, but knowing the order helps when reading code:

  1. Postfix: x++, x--, ., ?., !!, calls and indexing
  2. Prefix: -x, +x, ++x, --x, !x
  3. Multiplicative: *, /, %
  4. Additive: +, -
  5. Range: .., ..<
  6. Infix function: shl, and, to, your own infix functions
  7. Elvis: ?:
  8. Named checks: in, !in, is, !is
  9. Comparison: <, >, <=, >=
  10. Equality: ==, !=, ===, !==
  11. Conjunction: &&
  12. Disjunction: ||
  13. Assignment: =, +=, and the others

Because infix functions rank above comparison and equality, a and b == 0 is read as (a and b) == 0. Still, parentheses cost nothing.

Operators are function calls: a preview

Behind every operator is a function with a fixed name. a + b is a.plus(b), a[i] is a.get(i), a in b is b.contains(a), and a < b is a.compareTo(b) < 0. If you mark a function of your own with the operator modifier and give it one of those names, your class gets the operator:

Kotlin A first operator overload

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.

Overloading should make code more obvious: Money + Money reads naturally, but defining + to mean "send an email" would be a puzzle. The mechanics, the full list of overloadable operators and the rules for each are in Infix Functions and Operator Overloading and Operator Conventions.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does println(7 / 2) print?

    Both operands are Int, so the division is an integer division and the fraction is dropped. Use 7 / 2.0 for 3.5.
  2. 2. What does a == b compare for two lists in Kotlin?

    == is structural equality. === checks for the same object.
  3. 3. In check("A") && check("B"), when is check("B") skipped?

    && short-circuits: if the left side is false, the result must be false, so the right side is not evaluated.
  4. 4. How do you write the bitwise AND of a and b in Kotlin?

    Kotlin uses named infix functions such as and, or, xor, shl, shr and ushr instead of bit symbols. && is the logical operator for Booleans.
  5. 5. What is a < b translated to for a class with a compareTo function?

    The compiler rewrites comparison operators into a compareTo call and compares its result with zero.

Summary

  • Arithmetic follows operand types: Int / Int drops the fraction, % keeps the sign of the left operand, and integer division by zero throws.
  • == compares content (equals), === compares identity, and comparing Double values with == is risky.
  • && and || short-circuit; use them for guard conditions.
  • Assignment is a statement, += works on var or on mutable collections, and ++/-- have prefix and postfix forms.
  • Bitwise operations are the named functions and, or, xor, inv, shl, shr, ushr.
  • in, !in, is, !is and .. are operators too; precedence is the usual one, and parentheses are free.
  • Every operator is a function call, so your own classes can support operators with the operator modifier.

Next: if as an Expression