Kotlin Operators

Kotlin Operators

Operators in Kotlin are special symbols used to perform operations on variables and values. Kotlin provides a rich set of operators that are easy to understand and use.


1. Arithmetic Operators

Used for mathematical calculations.

Operator Description Example
+ Addition a + b
- Subtraction a - b
* Multiplication a * b
/ Division a / b
% Modulus a % b
val a = 10
val b = 3

println(a + b) // 13
println(a - b) // 7
println(a * b) // 30
println(a / b) // 3
println(a % b) // 1


2. Assignment Operators

Used to assign values.

Operator Example
= a = 5
+= a += 2
-= a -= 2
*= a *= 2
/= a /= 2
%= a %= 2
var x = 10
x += 5
println(x) // 15

3. Comparison (Relational) Operators

Used to compare values.

Operator Description
== Equal to
!= Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
val a = 10
val b = 20

println(a == b) // false
println(a != b) // true
println(a < b) // true


4. Logical Operators

Used to combine conditions.

Operator Description
&& AND
`
! NOT
val x = true
val y = false

println(x && y) // false
println(x || y) // true
println(!x) // false


5. Unary Operators

Used with a single operand.

Operator Description
++ Increment
-- Decrement
+ Unary plus
- Unary minus
! Logical NOT
var num = 5
num++
println(num) // 6

6. Range Operators

Used to create ranges.

Operator Example
.. 1..5
until 1 until 5
downTo 5 downTo 1
step 1..10 step 2
for (i in 1..5) {
println(i)
}

7. Bitwise Operators (Functions)

Kotlin uses functions instead of symbols.

Function Description
shl Shift left
shr Shift right
ushr Unsigned shift
and Bitwise AND
or Bitwise OR
xor Bitwise XOR
inv Invert bits
val a = 5
val b = 3

println(a and b)
println(a or b)


8. Elvis Operator ?:

Used for null handling.

val name: String? = null
val length = name?.length ?: 0
println(length)

9. Safe Call Operator ?.

val text: String? = "Kotlin"
println(text?.length)

Summary

  • Kotlin has powerful and readable operators

  • Supports null-safety operators

  • Bitwise operations use functions

  • Range operators simplify loops

You may also like...