Kotlin operators are predefined symbols that tell the compiler to perform specific mathematical, logical, or relational operations. The Kotlin programming language provides a rich set of operators that can be categorized into different types based on their functionality. These operators work with operands (variables, constants, or expressions) to produce results.
Kotlin operators are designed to be intuitive and follow familiar conventions from other programming languages while adding Kotlin-specific enhancements. The language supports operator overloading, which means you can define custom behavior for operators when working with your own classes.
Kotlin arithmetic operators perform mathematical operations on numeric values. These operators are essential for any calculations in your Kotlin applications.
The addition operator adds two operands together. In Kotlin, this operator can also be used for string concatenation.
val a = 10
val b = 5
val sum = a + b // Result: 15
val firstName = "John"
val lastName = "Doe"
val fullName = firstName + " " + lastName // Result: "John Doe"
The subtraction operator subtracts the right operand from the left operand.
val minuend = 20
val subtrahend = 8
val difference = minuend - subtrahend // Result: 12
The multiplication operator multiplies two operands.
val length = 7
val width = 4
val area = length * width // Result: 28
The division operator divides the left operand by the right operand. Kotlin operators handle integer and floating-point division differently.
val dividend = 15
val divisor = 4
val quotient = dividend / divisor // Result: 3 (integer division)
val preciseQuotient = 15.0 / 4.0 // Result: 3.75 (floating-point division)
The modulus operator returns the remainder after division.
val number = 17
val modulus = number % 5 // Result: 2
Kotlin assignment operators are used to assign values to variables. These operators combine assignment with arithmetic operations for concise code.
The basic assignment operator assigns the right operand’s value to the left operand.
var score = 100
var playerName = "Alice"
This compound assignment operator adds the right operand to the left operand and assigns the result to the left operand.
var total = 50
total += 25 // Equivalent to: total = total + 25
// total is now 75
The subtraction assignment operator subtracts the right operand from the left operand.
var health = 100
health -= 30 // health becomes 70
This operator multiplies the left operand by the right operand and assigns the result.
var damage = 15
damage *= 2 // damage becomes 30
The division assignment operator divides the left operand by the right operand.
var points = 120
points /= 3 // points becomes 40
This operator applies the modulus operation and assigns the result.
var value = 23
value %= 7 // value becomes 2
Kotlin comparison operators compare two values and return a Boolean result (true or false). These operators are crucial for conditional statements and loops.
Checks if two operands are equal in value.
val x = 10
val y = 10
val isEqual = x == y // Result: true
val name1 = "Kotlin"
val name2 = "Kotlin"
val namesEqual = name1 == name2 // Result: true
Checks if two operands are not equal in value.
val temperature1 = 25
val temperature2 = 30
val isDifferent = temperature1 != temperature2 // Result: true
Checks if the left operand is greater than the right operand.
val score1 = 85
val score2 = 72
val isHigher = score1 > score2 // Result: true
Checks if the left operand is less than the right operand.
val age = 16
val minimumAge = 18
val isTooYoung = age < minimumAge // Result: true
Checks if the left operand is greater than or equal to the right operand.
val currentLevel = 5
val requiredLevel = 5
val canAccess = currentLevel >= requiredLevel // Result: true
Checks if the left operand is less than or equal to the right operand.
val attempts = 3
val maxAttempts = 5
val withinLimit = attempts <= maxAttempts // Result: true
Kotlin logical operators are used to combine multiple Boolean conditions. These operators are essential for complex conditional logic.
Returns true only if both operands are true.
val hasPermission = true
val isLoggedIn = true
val canProceed = hasPermission && isLoggedIn // Result: true
val age = 20
val hasLicense = false
val canDrive = (age >= 18) && hasLicense // Result: false
Returns true if at least one operand is true.
val isWeekend = false
val isHoliday = true
val canRelax = isWeekend || isHoliday // Result: true
Inverts the Boolean value of the operand.
val isOnline = true
val isOffline = !isOnline // Result: false
val isEmpty = false
val hasContent = !isEmpty // Result: true
Kotlin unary operators operate on a single operand. These operators modify or return information about their operand.
Returns the value of the operand (identity operation).
val number = 42
val positive = +number // Result: 42
Returns the negative value of the operand.
val temperature = 25
val freezing = -temperature // Result: -25
Increases the value of a numeric operand by 1. Kotlin operators support both prefix and postfix increment.
var counter = 5
val preIncrement = ++counter // counter becomes 6, preIncrement is 6
var score = 10
val postIncrement = score++ // postIncrement is 10, then score becomes 11
Decreases the value of a numeric operand by 1.
var lives = 3
val preDecrement = --lives // lives becomes 2, preDecrement is 2
var energy = 100
val postDecrement = energy-- // postDecrement is 100, then energy becomes 99
Kotlin bitwise operators perform operations on individual bits of integer operands. These operators are useful for low-level programming and performance-critical applications.
Performs bitwise AND operation on each pair of corresponding bits.
val a = 12 // Binary: 1100
val b = 8 // Binary: 1000
val result = a and b // Result: 8 (Binary: 1000)
Performs bitwise OR operation on each pair of corresponding bits.
val x = 5 // Binary: 0101
val y = 3 // Binary: 0011
val result = x or y // Result: 7 (Binary: 0111)
Performs bitwise exclusive OR operation.
val num1 = 6 // Binary: 0110
val num2 = 4 // Binary: 0100
val result = num1 xor num2 // Result: 2 (Binary: 0010)
Inverts all bits of the operand.
val value = 5 // Binary: 00000101
val inverted = value.inv() // Result: -6 (Binary: 11111010 in two's complement)
Shifts bits to the left by specified positions.
val original = 3 // Binary: 0011
val shifted = original shl 2 // Result: 12 (Binary: 1100)
Shifts bits to the right by specified positions.
val value = 16 // Binary: 10000
val shifted = value shr 2 // Result: 4 (Binary: 00100)
Performs unsigned right shift operation.
val number = -8
val shifted = number ushr 2 // Performs unsigned right shift
Kotlin range operators create ranges of values, which are particularly useful in loops and conditional statements.
Creates an inclusive range from the first value to the second value.
val range = 1..10 // Creates range from 1 to 10 (inclusive)
val isInRange = 5 in range // Result: true
for (i in 1..5) {
println("Number: $i")
}
Creates a range that excludes the end value.
val exclusiveRange = 1 until 10 // Creates range from 1 to 9
val letters = 'a' until 'f' // Creates range from 'a' to 'e'
Creates a descending range.
val countdown = 10 downTo 1
for (i in countdown) {
println("Countdown: $i")
}
These Kotlin operators check membership and type information.
Checks if a value exists in a collection or range.
val numbers = listOf(1, 2, 3, 4, 5)
val contains = 3 in numbers // Result: true
val range = 10..20
val inRange = 15 in range // Result: true
val text = "Hello"
val hasChar = 'e' in text // Result: true
Checks if a value does not exist in a collection or range.
val fruits = listOf("apple", "banana", "orange")
val notFound = "grape" !in fruits // Result: true
Performs type checking.
val value: Any = "Hello Kotlin"
val isString = value is String // Result: true
val isInt = value is Int // Result: false
Checks if a value is not of a specific type.
val data: Any = 42
val notString = data !is String // Result: true
The Elvis operator (?:) is a unique Kotlin operator that provides a concise way to handle null values.
val name: String? = null
val displayName = name ?: "Unknown User" // Result: "Unknown User"
val length: Int? = null
val size = length ?: 0 // Result: 0
fun getUserName(user: User?): String {
return user?.name ?: "Guest"
}
The safe call operator (?.) allows safe navigation through potentially null references.
val user: User? = getUser()
val userName = user?.name // Returns null if user is null
val address = user?.profile?.address?.street
// Chain of safe calls - returns null if any link is null
val upperCaseName = user?.name?.uppercase()
// Safe call with method invocation
Here’s a comprehensive example demonstrating various Kotlin operators in a practical scenario:
// Import statements (none needed for basic operators)
fun main() {
println("=== Kotlin Operators Demo ===\n")
// Arithmetic Operators
val base = 10
val multiplier = 3
val addition = base + multiplier // 13
val subtraction = base - multiplier // 7
val multiplication = base * multiplier // 30
val division = base / multiplier // 3
val modulus = base % multiplier // 1
println("Arithmetic Operations:")
println("$base + $multiplier = $addition")
println("$base - $multiplier = $subtraction")
println("$base * $multiplier = $multiplication")
println("$base / $multiplier = $division")
println("$base % $multiplier = $modulus\n")
// Assignment Operators
var score = 100
println("Assignment Operations:")
println("Initial score: $score")
score += 25 // score becomes 125
println("After += 25: $score")
score -= 15 // score becomes 110
println("After -= 15: $score")
score *= 2 // score becomes 220
println("After *= 2: $score")
score /= 4 // score becomes 55
println("After /= 4: $score")
score %= 10 // score becomes 5
println("After %= 10: $score\n")
// Comparison Operators
val player1Score = 85
val player2Score = 92
println("Comparison Operations:")
println("Player 1: $player1Score, Player 2: $player2Score")
println("Equal: ${player1Score == player2Score}")
println("Not Equal: ${player1Score != player2Score}")
println("Player 1 > Player 2: ${player1Score > player2Score}")
println("Player 1 < Player 2: ${player1Score < player2Score}")
println("Player 1 >= 85: ${player1Score >= 85}")
println("Player 2 <= 100: ${player2Score <= 100}\n")
// Logical Operators
val hasPermission = true
val isLoggedIn = true
val isAdmin = false
println("Logical Operations:")
println("Has Permission: $hasPermission")
println("Is Logged In: $isLoggedIn")
println("Is Admin: $isAdmin")
println("Can Access: ${hasPermission && isLoggedIn}")
println("Special Access: ${isAdmin || (hasPermission && isLoggedIn)}")
println("Is Guest: ${!isLoggedIn}\n")
// Unary Operators
var counter = 5
println("Unary Operations:")
println("Initial counter: $counter")
println("Pre-increment: ${++counter}") // counter becomes 6
println("Post-increment: ${counter++}") // returns 6, counter becomes 7
println("Current counter: $counter")
println("Pre-decrement: ${--counter}") // counter becomes 6
println("Post-decrement: ${counter--}") // returns 6, counter becomes 5
println("Final counter: $counter\n")
// Range Operators
println("Range Operations:")
val range1to10 = 1..10
val range1to9 = 1 until 10
val rangeCountdown = 5 downTo 1
println("Numbers 1 to 5:")
for (i in 1..5) {
print("$i ")
}
println()
println("Countdown from 5:")
for (i in rangeCountdown) {
print("$i ")
}
println("\n")
// In and Is Operators
val numbers = listOf(1, 2, 3, 4, 5)
val searchValue = 3
val testValue: Any = "Hello Kotlin"
println("In and Is Operations:")
println("$searchValue in $numbers: ${searchValue in numbers}")
println("10 not in $numbers: ${10 !in numbers}")
println("Test value is String: ${testValue is String}")
println("Test value is not Int: ${testValue !is Int}\n")
// Elvis and Safe Call Operators
val nullableString: String? = null
val user: User? = User("John Doe", 25)
println("Null Safety Operations:")
println("Nullable string or default: ${nullableString ?: "Default Value"}")
println("User name safely: ${user?.name}")
println("User age safely: ${user?.age}")
val nullUser: User? = null
println("Null user name safely: ${nullUser?.name ?: "Unknown User"}")
// Bitwise Operations
println("\nBitwise Operations:")
val a = 12 // 1100 in binary
val b = 8 // 1000 in binary
println("$a (1100) and $b (1000) = ${a and b}")
println("$a (1100) or $b (1000) = ${a or b}")
println("$a (1100) xor $b (1000) = ${a xor b}")
println("$a shifted left by 2: ${a shl 2}")
println("$a shifted right by 2: ${a shr 2}")
}
// Helper class for demonstration
data class User(val name: String, val age: Int)
Output:
=== Kotlin Operators Demo ===
Arithmetic Operations:
10 + 3 = 13
10 - 3 = 7
10 * 3 = 30
10 / 3 = 3
10 % 3 = 1
Assignment Operations:
Initial score: 100
After += 25: 125
After -= 15: 110
After *= 2: 220
After /= 4: 55
After %= 10: 5
Comparison Operations:
Player 1: 85, Player 2: 92
Equal: false
Not Equal: true
Player 1 > Player 2: false
Player 1 < Player 2: true
Player 1 >= 85: true
Player 2 <= 100: true
Logical Operations:
Has Permission: true
Is Logged In: true
Is Admin: false
Can Access: true
Special Access: true
Is Guest: false
Unary Operations:
Initial counter: 5
Pre-increment: 6
Post-increment: 6
Current counter: 7
Pre-decrement: 6
Post-decrement: 6
Final counter: 5
Range Operations:
Numbers 1 to 5:
1 2 3 4 5
Countdown from 5:
5 4 3 2 1
In and Is Operations:
3 in [1, 2, 3, 4, 5]: true
10 not in [1, 2, 3, 4, 5]: true
Test value is String: true
Test value is not Int: true
Null Safety Operations:
Nullable string or default: Default Value
User name safely: John Doe
User age safely: 25
Null user name safely: Unknown User
Bitwise Operations:
12 (1100) and 8 (1000) = 8
12 (1100) or 8 (1000) = 12
12 (1100) xor 8 (1000) = 4
12 shifted left by 2: 48
12 shifted right by 2: 3
Understanding and mastering Kotlin operators is essential for effective Kotlin programming. These operators provide the foundation for mathematical calculations, logical operations, comparisons, and null safety handling that make Kotlin such a powerful and expressive programming language.