Kotlin Operators Cheat Sheet: A Comprehensive Guide
Kotlin’s operator system is a blend of familiar concepts from other languages and unique features that contribute to its conciseness and readability. This cheat sheet provides a comprehensive overview of Kotlin operators, their precedence, and how they work, making it a valuable reference for both beginners and experienced Kotlin developers.
I. Operator Precedence and Associativity
Kotlin operators are evaluated in a specific order based on their precedence. Operators with higher precedence are evaluated before those with lower precedence. When operators have the same precedence, associativity determines the order of evaluation (left-to-right or right-to-left). Here’s a table summarizing the precedence and associativity (highest precedence first):
| Precedence | Operator(s) | Associativity | Description |
|————|————————————————|—————–|———————————————————–|
| 1 | ++
, --
(postfix) | Left-to-right | Postfix increment/decrement |
| 2 | +
, -
(unary), !
, ++
, --
(prefix) | Right-to-left | Unary plus/minus, logical NOT, prefix increment/decrement |
| 3 | *
, /
, %
| Left-to-right | Multiplication, division, modulo |
| 4 | +
, -
(binary) | Left-to-right | Addition, subtraction |
| 5 | ..
, ..<
| Left-to-right | Range operators (inclusive and exclusive) |
| 6 | in
, !in
| Left-to-right | Membership check |
| 7 | is
, !is
| Left-to-right | Type check |
| 8 | <
, <=
, >
, >=
| Left-to-right | Comparison operators |
| 9 | ==
, !=
| Left-to-right | Equality operators |
| 10 | &&
| Left-to-right | Logical AND |
| 11 | \|\|
| Left-to-right | Logical OR |
| 12 | ?:
(Elvis operator) | Right-to-left | Null-safe operator (ternary conditional) |
| 13 | =
, +=
, -=
, *=
, /=
, %=
| Right-to-left | Assignment operators |
II. Operator Categories and Examples
Let’s explore each category with detailed explanations and code examples.
1. Arithmetic Operators:
+
(addition):val sum = 5 + 3 // sum = 8
-
(subtraction):val diff = 10 - 4 // diff = 6
*
(multiplication):val product = 2 * 7 // product = 14
/
(division):val quotient = 15 / 3 // quotient = 5
%
(modulo – remainder):val remainder = 17 % 5 // remainder = 2
+
(unary plus):val positive = +5 // positive = 5 (no effect)
-
(unary minus):val negative = -5 // negative = -5
2. Increment and Decrement Operators:
++
(increment): Increases the value by 1.- Prefix:
++x
(increments before the value is used). - Postfix:
x++
(increments after the value is used).
- Prefix:
--
(decrement): Decreases the value by 1.- Prefix:
--x
(decrements before the value is used). - Postfix:
x--
(decrements after the value is used).
- Prefix:
“`kotlin
var a = 5
println(a++) // Prints 5, then a becomes 6
println(a) // Prints 6
var b = 10
println(++b) // Prints 11, b becomes 11
println(b) // Prints 11
“`
3. Range Operators:
..
(inclusive range): Creates a range that includes both the start and end values...<
(exclusive range): Creates a range that includes the start value but excludes the end value.
“`kotlin
for (i in 1..5) { // Iterates from 1 to 5 (inclusive)
println(i) // Prints 1, 2, 3, 4, 5
}
for (i in 1..<5) { // Iterates from 1 to 4 (exclusive)
println(i) // Prints 1, 2, 3, 4
}
val range = 10..20
println(15 in range) // Prints true
“`
4. Membership Operators (in
, !in
):
in
: Checks if a value is within a range or collection.!in
: Checks if a value is not within a range or collection.
kotlin
val numbers = listOf(1, 2, 3, 4, 5)
println(3 in numbers) // Prints true
println(6 in numbers) // Prints false
println(6 !in numbers) // Prints true
5. Type Check Operators (is
, !is
):
is
: Checks if an object is of a specific type.!is
: Checks if an object is not of a specific type.
kotlin
val str: Any = "Hello"
if (str is String) {
println(str.length) // Smart cast: str is treated as String inside the if block
}
if(str !is Int){
println("Not an integer")
}
6. Comparison Operators:
<
(less than):5 < 10 // true
<=
(less than or equal to):5 <= 5 // true
>
(greater than):10 > 5 // true
>=
(greater than or equal to):10 >= 10 // true
7. Equality Operators:
==
(equals): Checks for structural equality (values are the same). Uses theequals()
method.!=
(not equals): Checks for structural inequality.===
(referential equality): Checks if two references point to the same object in memory.!==
(referential inequality): Checks if two references point to different objects in memory.
“`kotlin
val str1 = “hello”
val str2 = “hello”
val str3 = String(“hello”.toCharArray())
println(str1 == str2) // Prints true (structural equality)
println(str1 === str2) // Prints true (referential equality – string interning)
println(str1 == str3) // Prints true (structural equality)
println(str1 === str3) // Prints false (referential inequality)
data class Person(val name: String)
val p1 = Person(“Alice”)
val p2 = Person(“Alice”)
val p3 = p1
println(p1 == p2) //Prints true (data classes have equals() based on content)
println(p1 === p2) // Prints false
println(p1 === p3) // Prints true
“`
8. Logical Operators:
&&
(logical AND): Returnstrue
only if both operands aretrue
. Short-circuiting: if the left operand isfalse
, the right operand is not evaluated.||
(logical OR): Returnstrue
if either operand istrue
. Short-circuiting: if the left operand istrue
, the right operand is not evaluated.!
(logical NOT): Reverses the boolean value.!true
isfalse
, and!false
istrue
.
kotlin
val x = 5
val y = 10
println(x > 0 && y < 20) // Prints true
println(x > 10 || y > 5) // Prints true (x > 10 is false, but y > 5 is true)
println(!(x > 0)) // Prints false
9. Elvis Operator (?:
):
?:
: Provides a concise way to handle null values. If the expression on the left is not null, it returns the expression on the left. Otherwise, it returns the expression on the right. Essentially a shorthand for a ternary operator.
“`kotlin
val name: String? = null
val length = name?.length ?: 0 // length will be 0 because name is null
println(length)
val name2: String? = “Alice”
val length2 = name2?.length ?: 0 //length will be 5
println(length2)
“`
10. Assignment Operators:
=
(assignment): Assigns the value on the right to the variable on the left.+=
,-=
,*=
,/=
,%=
: Compound assignment operators. Perform the operation and assign the result to the variable on the left.
kotlin
var num = 10
num += 5 // Equivalent to num = num + 5; num becomes 15
num -= 3 // num becomes 12
num *= 2 // num becomes 24
num /= 4 // num becomes 6
num %= 5 // num becomes 1
III. Operator Overloading
Kotlin allows you to define the behavior of operators for your own classes. This is called operator overloading. You use the operator
keyword followed by the function name corresponding to the operator.
“`kotlin
data class Point(val x: Int, val y: Int) {
operator fun plus(other: Point): Point {
return Point(x + other.x, y + other.y)
}
operator fun unaryMinus(): Point {
return Point(-x, -y)
}
}
fun main() {
val p1 = Point(1, 2)
val p2 = Point(3, 4)
val p3 = p1 + p2 // Uses the overloaded plus operator
println(p3) // Prints Point(x=4, y=6)
val p4 = -p1 // Uses the overloaded unaryMinus operator
println(p4) // Prints Point(x=-1, y=-2)
}
“`
Here’s a table of common overloads:
| Operator | Function Name |
|———-|———————–|
| +a
| unaryPlus()
|
| -a
| unaryMinus()
|
| !a
| not()
|
| a++
| inc()
|
| a--
| dec()
|
| a + b
| plus(b)
|
| a - b
| minus(b)
|
| a * b
| times(b)
|
| a / b
| div(b)
|
| a % b
| rem(b)
or mod(b)
|
| a..b
| rangeTo(b)
|
| a in b
| contains(a)
|
| a[i]
| get(i)
|
| a[i,j]
|get(i,j)
|
| a[i] = b
|set(i, b)
|
| a[i,j] = b
| set(i, j, b)
|
| a == b
| equals(b)
|
| a > b
| compareTo(b) > 0
|
| a < b
| compareTo(b) < 0
|
| a >= b
| compareTo(b) >= 0
|
| a <= b
| compareTo(b) <= 0
|
| a += b
| plusAssign(b)
|
|a && b
| and(b)
|
|a || b
| or(b)
|
|a?.b
| (Compiler handles null-safe calls) |
|a!!
| (Compiler handles non-null assertions) |
IV. Conclusion
This cheat sheet provides a thorough understanding of Kotlin’s operators, covering their precedence, usage, and overloading capabilities. Mastering these operators is crucial for writing efficient and expressive Kotlin code. Remember to consult this guide whenever you need a quick refresher on operator behavior. By understanding operator precedence and overloading capabilities, you’ll be well-equipped to write clean, concise, and powerful Kotlin code.