Kotlin Operators Explained (2025 Guide to Arithmetic, Logical & Comparison Operators)
In 2025, Kotlin’s operators make coding intuitive and efficient, from math to logic and beyond. 🌟 Whether you’re crunching numbers, comparing values, or tweaking bits, this guide covers every operator with beginner-friendly clarity and pro-level depth! 🎉
- 🔢 Arithmetic: Math operations like add, subtract, and more. 🧮
- ⚖️ Relational: Compare values for decisions. 📊
- 📝 Assignment: Set and update variables with ease. ✍️
- 🔧 Unary: Work with single values for quick tweaks. ⚡
- ⚙️ Bitwise: Manipulate bits for low-level magic. 🔩
- 🤓 Logical: Build smart conditions for control flow. 🧠
Arithmetic Operators 🔢
- ➕ Add: Combines two numbers. 📈
- ➖ Subtract: Finds the difference. 📉
- ✖️ Multiply: Scales values. 📊
- ➗ Divide: Splits numbers (beware of zero!). ⚠️
- 📊 Modulus: Returns the remainder after division. 🔢
Operator | Description | Expression | Translate to | Example |
---|---|---|---|---|
+ | Addition ➕ | a+b | a.plus(b) | 5+3=8 |
- | Subtraction ➖ | a-b | a.minus(b) | 5-3=2 |
* | Multiply ✖️ | a*b | a.times(b) | 5*3=15 |
/ | Division ➗ | a/b | a.div(b) | 6/2=3 |
% | Modulus 📊 | a%b | a.rem(b) | 5%2=1 |
Example: Perform arithmetic calculations:
fun main() {
var result = 5 + 3 // ➕ Adds to 8
result = result / 2 // ➗ Divides to 4
result = result * 5 // ✖️ Multiplies to 20
result = result - 1 // ➖ Subtracts to 19
val moduloResult = 5 % 2 // 📊 Remainder is 1
println("Result: $result") // Outputs: Result: 19 📊
println("Modulo: $moduloResult") // Outputs: Modulo: 1 📊
}
Pro Tip: Watch for division by zero—it throws an ArithmeticException! ⚠️
Relational Operators ⚖️
- 📈 Greater Than: Checks if one value exceeds another. 🔝
- 📉 Less Than: Tests if a value is below another. 🔽
- ⚖️ Equal/Not Equal: Compares for sameness or difference. ✅❌
- 🔍 Inclusive Checks: Includes equality with >= or <=. 📊
Operator | Description | Expression | Translate to | Example |
---|---|---|---|---|
> | Greater than 📈 | a>b | a.compareTo(b)>0 | 5>3=true |
< | Less than 📉 | a | a.compareTo(b)<0 | 3<5=true |
>= | Greater than or equal to ⚖️ | a>=b | a.compareTo(b)>=0 | 5>=5=true |
<= | Less than or equal to ⚖️ | a<=b | a.compareTo(b)<=0 | 3<=5=true |
== | Is equal to ✅ | a==b | a?.equals(b) ?: (b===null) | 5==5=true |
!= | Not equal to ❌ | a!=b | !(a?.equals(b) ?: (b===null)) | 5!=3=true |
Example: Compare values for decisions:
fun main() {
val a = 5
val b = 3
println("isEqual: ${a == b}") // Outputs: isEqual: false 📊
println("isNotEqual: ${a != b}") // Outputs: isNotEqual: true 📊
println("isGreater: ${a > b}") // Outputs: isGreater: true 📊
println("isLessEqual: ${a <= b}") // Outputs: isLessEqual: false 📊
}
Relational Tip: Use === for reference equality with objects; == checks value equality. 🔍
Assignment Operators 📝
- ➕ Add-Assign: Adds and updates in one step. 📈
- ➖ Subtract-Assign: Subtracts and assigns. 📉
- ✖️ Multiply-Assign: Multiplies and sets. 📊
- ➗ Divide-Assign: Divides and updates. ⚖️
- 📊 Mod-Assign: Applies modulus and assigns. 🔢
Operator | Description | Expression | Convert to | Example |
---|---|---|---|---|
+= | Add and assign ➕ | a+=b | a.plusAssign(b) | a=5; a+=3 → a=8 |
-= | Subtract and assign ➖ | a-=b | a.minusAssign(b) | a=5; a-=3 → a=2 |
*= | Multiply and assign ✖️ | a*=b | a.timesAssign(b) | a=5; a*=3 → a=15 |
/= | Divide and assign ➗ | a/=b | a.divAssign(b) | a=6; a/=2 → a=3 |
%= | Mod and assign 📊 | a%=b | a.remAssign(b) | a=5; a%=2 → a=1 |
Example: Update variables efficiently:
fun main() {
var myNum = 5 // 📝 Initial value
myNum += 3 // ➕ Adds 3, myNum = 8
println("myNum: $myNum") // Outputs: myNum: 8 📊
myNum *= 4 // ✖️ Multiplies by 4, myNum = 32
println("myNum: $myNum") // Outputs: myNum: 32 📊
}
Assignment Tip: Use compound assignments (+=, etc.) for concise updates, but ensure type compatibility! 🛠️
Unary Operators 🔧
- ➕ Unary Plus: Affirms a positive value. 📈
- ➖ Unary Minus: Flips to negative. 📉
- ⬆️ Increment: Adds 1 (pre/post). 🔝
- ⬇️ Decrement: Subtracts 1 (pre/post). 🔽
- 🚫 Not: Inverts a boolean. 🔄
Operator | Description | Expression | Convert to | Example |
---|---|---|---|---|
+ | Unary plus ➕ | +a | a.unaryPlus() | +5=5 |
- | Unary minus ➖ | -a | a.unaryMinus() | -5=-5 |
++ | Increment by 1 ⬆️ | ++a | a.inc() | a=5; ++a=6 |
-- | Decrement by 1 ⬇️ | --a | a.dec() | a=5; --a=4 |
! | Not 🚫 | !a | a.not() | !true=false |
Example: Use unary operators for quick changes:
fun main() {
var counter = 5 // 📝 Initial value
counter++ // ⬆️ Post-increment to 6
println("Post-increment: $counter") // Outputs: Post-increment: 6 📊
println("Pre-increment: ${++counter}") // Outputs: Pre-increment: 7 📊
val flag = true
println("Not: ${!flag}") // Outputs: Not: false 📊
}
Unary Tip: Pre-increment (++a) changes before use; post-increment (a++) changes after use. 🔍
Logical Operators 🤓
- ✅ AND: True if all conditions are true. 🔗
- ✅ OR: True if any condition is true. 🔀
- 🚫 NOT: Flips true to false and vice versa. 🔄
- 🔍 Short-Circuiting: Stops evaluating once the result is clear. ⚡
Operator | Description | Expression | Convert to | Example |
---|---|---|---|---|
&& | True if all are true ✅ | (a>b) && (a>c) | (a>b) and (a>c) | (5>3)&&(5>2)=true |
|| | True if any are true ✅ | (a>b) || (a>c) | (a>b) or (a>c) | (5>3)||(3>5)=true |
! | Complement (not) 🚫 | !a | a.not() | !true=false |
Example: Combine conditions for logic:
fun main() {
val a = 5
val b = 3
val c = 2
println("AND: ${(a > b) && (a > c)}") // Outputs: AND: true 📊
println("OR: ${(a > b) || (a < c)}") // Outputs: OR: true 📊
println("NOT: ${!(a == b)}") // Outputs: NOT: true 📊
}
Logical Tip: Use parentheses to clarify complex conditions and leverage short-circuiting for efficiency. ⚡
Bitwise Operations ⚙️
- ⬅️ Shift Left: Moves bits left, filling with zeros. 📈
- ➡️ Shift Right: Moves bits right, signed or unsigned. 📉
- 🔗 AND/OR/XOR: Combines bits logically. 🔀
- 🔄 Inverse: Flips all bits. ⚙️
Named Function | Description | Expression | Example |
---|---|---|---|
shl(bits) | Signed shift left ⬅️ | a.shl(b) | 5.shl(1)=10 |
shr(bits) | Signed shift right ➡️ | a.shr(b) | 10.shr(1)=5 |
ushr(bits) | Unsigned shift right ➡️ | a.ushr(b) | -10.ushr(1)=2147483643 |
and(bits) | Bitwise AND 🔗 | a.and(b) | 5.and(3)=1 |
or(bits) | Bitwise OR 🔗 | a.or(b) | 5.or(3)=7 |
xor(bits) | Bitwise XOR 🔀 | a.xor(b) | 5.xor(3)=6 |
inv() | Bitwise inverse 🔄 | a.inv() | 5.inv()=-6 |
Example: Manipulate bits for flags:
fun main() {
val a = 5 // Binary: 0101 🌟
val b = 3 // Binary: 0011 🌟
println("Shift Left: ${a.shl(1)}") // Outputs: Shift Left: 10 📊
println("AND: ${a.and(b)}") // Outputs: AND: 1 📊
println("OR: ${a.or(b)}") // Outputs: OR: 7 📊
}
Bitwise Tip: Use bitwise ops for flags, masks, or performance-critical code, but ensure clear documentation! 🛠️
Special Operators: Elvis, Safe Call, and More 🌈
- 🛡️ Elvis (?:): Provides a default if null. 🎸
- 🔍 Safe Call (?.): Accesses properties safely for nullable types. 🛠️
- 📏 Range (..): Creates inclusive ranges for loops or checks. 🔢
- 🔗 in: Checks if a value is in a range or collection. ✅
Example: Handle nulls and ranges:
fun main() {
val name: String? = null // 🌈 Nullable string
println(name?.length ?: 0) // Outputs: 0 📊
val score = 75
println("In Range: ${score in 0..100}") // Outputs: In Range: true 📊
}
Special Tip: Combine ?. and ?: for robust null handling in production code! 🛡️
Operator Overloading 🎨
Example: Overload + for a custom class:
data class Point(val x: Int, val y: Int) {
operator fun plus(other: Point) = Point(x + other.x, y + other.y) // ➕ Custom addition
}
fun main() {
val p1 = Point(1, 2)
val p2 = Point(3, 4)
val sum = p1 + p2 // 🌟 Uses overloaded +
println("Sum: (${sum.x}, ${sum.y})") // Outputs: Sum: (4, 6) 📊
}
Overloading Tip: Use sparingly and document clearly to avoid confusion! 📝
Integrated Example from Original Code 🧩
fun main() {
// 🔢 Arithmetic operators
var result = 5 + 3 // ➕ Adds to 8
result = result / 2 // ➗ Divides to 4
// Alternatively: result /= 2
result = result * 5 // ✖️ Multiplies to 20
result = result - 1 // ➖ Subtracts to 19
var moduloResult = 5 % 2 // 📊 Remainder is 1
println("Modulo: $moduloResult") // Outputs: Modulo: 1 📊
// ⚖️ Comparison operators
val isEqual = 5 == 3 // ✅ False
println("isEqual is $isEqual") // Outputs: isEqual is false 📊
val isNotEqual = 5 != 5 // ❌ False
println("isNotEqual is $isNotEqual") // Outputs: isNotEqual is false 📊
println("is5Greater3 ${5 > 3}") // Outputs: is5Greater3 true 📊
println("is5LowerEqual3 ${5 >= 3}") // Outputs: is5LowerEqual3 true 📊
println("is5LowerEqual5 ${5 >= 5}") // Outputs: is5LowerEqual5 true 📊
// 📝 Assignment operators
var myNum = 5 // 📝 Initial value
myNum += 3 // ➕ Adds 3, myNum = 8
println("myNum is $myNum") // Outputs: myNum is 8 📊
myNum *= 4 // ✖️ Multiplies by 4, myNum = 32
println("myNum is $myNum") // Outputs: myNum is 32 📊
// 🔧 Increment & Decrement operators
myNum++ // ⬆️ Post-increment to 33
println("myNum is $myNum") // Outputs: myNum is 33 📊
println("myNum is ${myNum++}") // Outputs: myNum is 33 (then myNum = 34) 📊
println("myNum is ${++myNum}") // Outputs: myNum is 35 (pre-increment) 📊
println("myNum is ${--myNum}") // Outputs: myNum is 34 (pre-decrement) 📊
}
Integrated Tip: Combine operators thoughtfully to keep code readable and maintainable. 🧩
Best Practices for Using Operators ✅
- 🧠 Clarity First: Use parentheses to clarify complex expressions (e.g., (a + b) * c). 📝
- ⚠️ Avoid Errors: Check for division by zero or nulls before operations. 🛡️
- 🔍 Reference vs. Value: Use == for value equality, === for reference equality with objects. 🔗
- ⚡ Optimize Bitwise: Use bitwise ops only when necessary (e.g., flags); document their purpose. ⚙️
- 🛠️ Null Safety: Pair operators with ?. and ?: for nullable types. 🌈
- 🎨 Overload Wisely: Overload operators for intuitive behavior, like + for custom types. 📚
Frequently Asked Questions (FAQ) ❓
- What’s the difference between == and ===? 🤔
== checks value equality; === checks reference equality for objects. Use == for most comparisons. 🔍 - How do I handle division by zero? ⚠️
Check the divisor before division or catch ArithmeticException to avoid crashes. 🛡️ - Why use named functions for bitwise operations? ⚙️
Kotlin’s named functions (shl, and) are clearer than symbols and align with its operator overloading philosophy. 📚 - What’s the Elvis operator? 🎸
?: provides a default value if an expression is null, enhancing null safety. 🛡️ - Can I overload operators for my classes? 🎨
Yes, use operator functions like plus to redefine operators for custom types. 🛠️ - How do short-circuiting logical operators work? ⚡
&& stops if the first condition is false; || stops if the first is true, saving computation. 🧠
Comments
Post a Comment