Kotlin Operators
Operators are special symbols that perform operations on variables and values. Kotlin provides a rich set of operators that help you perform various operations like arithmetic calculations, comparisons, logical operations, and more.
Introduction to Kotlin Operators
In programming, operators are symbols that tell the compiler to perform specific mathematical, relational, or logical operations. Kotlin offers a variety of operators categorized based on their functions:
- Arithmetic Operators
- Assignment Operators
- Comparison Operators
- Logical Operators
- Bitwise Operators
- Range Operators
- Special Operators
Understanding these operators is fundamental to writing efficient Kotlin code, and they form the building blocks of more complex operations in your applications.
Arithmetic Operators
Arithmetic operators are used to perform basic mathematical operations.
Operator | Name | Description |
---|---|---|
+ | Addition | Adds two values |
- | Subtraction | Subtracts the right operand from the left |
* | Multiplication | Multiplies two values |
/ | Division | Divides the left operand by the right one |
% | Modulus | Returns the remainder after division |
Example of Arithmetic Operators
fun main() {
val a = 10
val b = 3
println("Addition: ${a + b}") // Output: Addition: 13
println("Subtraction: ${a - b}") // Output: Subtraction: 7
println("Multiplication: ${a * b}") // Output: Multiplication: 30
println("Division: ${a / b}") // Output: Division: 3
println("Modulus: ${a % b}") // Output: Modulus: 1
// Float division
println("Float division: ${a.toFloat() / b}") // Output: Float division: 3.3333333
}
Assignment Operators
Assignment operators are used to assign values to variables.
Operator | Example | Equivalent To |
---|---|---|
= | a = b | a = b |
+= | a += b | a = a + b |
-= | a -= b | a = a - b |
*= | a *= b | a = a * b |
/= | a /= b | a = a / b |
%= | a %= b | a = a % b |
Example of Assignment Operators
fun main() {
var x = 10
println("Initial value of x: $x") // Output: Initial value of x: 10
x += 5
println("After x += 5: $x") // Output: After x += 5: 15
x -= 3
println("After x -= 3: $x") // Output: After x -= 3: 12
x *= 2
println("After x *= 2: $x") // Output: After x *= 2: 24
x /= 4
println("After x /= 4: $x") // Output: After x /= 4: 6
x %= 4
println("After x %= 4: $x") // Output: After x %= 4: 2
}
Comparison Operators
Comparison operators are used to compare two values. They return a Boolean result (true
or false
).
Operator | Name | Description |
---|---|---|
== | Equal to | Returns true if both operands are equal |
!= | Not equal to | Returns true if operands are not equal |
> | Greater than | Returns true if left operand is greater than right |
< | Less than | Returns true if left operand is less than right |
>= | Greater than or equal to | Returns true if left operand is greater than or equal to right |
<= | Less than or equal to | Returns true if left operand is less than or equal to right |
Example of Comparison Operators
fun main() {
val a = 10
val b = 20
println("a == b: ${a == b}") // Output: a == b: false
println("a != b: ${a != b}") // Output: a != b: true
println("a > b: ${a > b}") // Output: a > b: false
println("a < b: ${a < b}") // Output: a < b: true
println("a >= b: ${a >= b}") // Output: a >= b: false
println("a <= b: ${a <= b}") // Output: a <= b: true
// Comparing strings
val str1 = "Hello"
val str2 = "Hello"
println("str1 == str2: ${str1 == str2}") // Output: str1 == str2: true
}
Logical Operators
Logical operators are used to determine the logic between variables or values.
Operator | Name | Description |
---|---|---|
&& | Logical AND | Returns true if both statements are true |
|| | Logical OR | Returns true if one of the statements is true |
! | Logical NOT | Reverses the result, returns false if the result is true |
Example of Logical Operators
fun main() {
val a = true
val b = false
println("a && b: ${a && b}") // Output: a && b: false
println("a || b: ${a || b}") // Output: a || b: true
println("!a: ${!a}") // Output: !a: false
// Practical example
val age = 25
val hasPermission = true
if (age >= 18 && hasPermission) {
println("Access granted") // This will be printed
} else {
println("Access denied")
}
}
Bitwise Operators
Kotlin provides infix functions for bitwise operations on integers.
Operation | Method | Description |
---|---|---|
Bitwise AND | and() | Returns 1 if both bits are 1 |
Bitwise OR | or() | Returns 1 if at least one bit is 1 |
Bitwise XOR | xor() | Returns 1 if exactly one bit is 1 |
Bitwise Inversion | inv() | Inverts all bits |
Left Shift | shl() | Shifts bits to the left |
Right Shift | shr() | Shifts bits to the right |
Unsigned Right Shift | ushr() | Shifts bits to the right, filling with zeros |
Example of Bitwise Operations
fun main() {
val a = 12 // Binary: 1100
val b = 10 // Binary: 1010
println("a and b: ${a and b}") // Output: a and b: 8 (Binary: 1000)
println("a or b: ${a or b}") // Output: a or b: 14 (Binary: 1110)
println("a xor b: ${a xor b}") // Output: a xor b: 6 (Binary: 0110)
println("a.inv(): ${a.inv()}") // Output: a.inv(): -13 (Binary: inversion of 1100)
println("a shl 2: ${a shl 2}") // Output: a shl 2: 48 (Binary: 110000)
println("a shr 2: ${a shr 2}") // Output: a shr 2: 3 (Binary: 11)
// Unsigned right shift example
val negative = -8
println("negative shr 1: ${negative shr 1}") // Output: negative shr 1: -4
println("negative ushr 1: ${negative ushr 1}") // Output: depends on bit length, but will be positive
}
Range Operators
Kotlin provides range operators to create ranges of values.
Operator | Description |
---|---|
.. | Creates an inclusive range |
until | Creates a range excluding the end element |
downTo | Creates a range that goes backward |
step | Defines the increment step for the range |
Example of Range Operators
fun main() {
// Inclusive range (1 to 5)
for (i in 1..5) {
print("$i ") // Output: 1 2 3 4 5
}
println()
// Exclusive range (1 to 4)
for (i in 1 until 5) {
print("$i ") // Output: 1 2 3 4
}
println()
// Descending range (5 down to 1)
for (i in 5 downTo 1) {
print("$i ") // Output: 5 4 3 2 1
}
println()
// Range with step
for (i in 1..10 step 2) {
print("$i ") // Output: 1 3 5 7 9
}
println()
// Check if a value is in a range
val x = 3
if (x in 1..5) {
println("$x is in range") // Output: 3 is in range
}
}
Special Kotlin Operators
Kotlin introduces several special operators that make your code more expressive.
Elvis Operator (?:
)
Used for null safety, returns the left expression if it's not null, otherwise returns the right expression.
fun main() {
val name: String? = null
val displayName = name ?: "Unknown"
println(displayName) // Output: Unknown
val anotherName: String? = "Alice"
val anotherDisplayName = anotherName ?: "Unknown"
println(anotherDisplayName) // Output: Alice
}
Safe Call Operator (?.
)
Calls a method or accesses a property only if the reference is non-null.
fun main() {
val name: String? = null
println(name?.length) // Output: null
val anotherName: String? = "Alice"
println(anotherName?.length) // Output: 5
}
Not-null Assertion Operator (!!
)
Converts a nullable type to a non-null type and throws a NullPointerException
if the value is null.
fun main() {
val name: String? = "Alice"
println(name!!.length) // Output: 5
// This would throw a NullPointerException
// val nullName: String? = null
// println(nullName!!.length)
}
Smart Casts and is
Operator
Kotlin automatically casts an object after it's been checked with the is
operator.
fun main() {
val obj: Any = "Hello"
if (obj is String) {
// obj is automatically cast to String
println("String length: ${obj.length}") // Output: String length: 5
}
when (obj) {
is String -> println("It's a String") // Output: It's a String
is Int -> println("It's an Int")
else -> println("Unknown type")
}
}
Operator Overloading
One of Kotlin's powerful features is operator overloading, which allows you to define how operators work with your custom classes.
data class Point(val x: Int, val y: Int) {
// Overloading the + operator
operator fun plus(other: Point): Point {
return Point(x + other.x, y + other.y)
}
// Overloading the - operator
operator fun minus(other: Point): Point {
return Point(x - other.x, y - other.y)
}
}
fun main() {
val p1 = Point(10, 20)
val p2 = Point(5, 15)
// Using the overloaded + operator
val sum = p1 + p2
println("Sum: $sum") // Output: Sum: Point(x=15, y=35)
// Using the overloaded - operator
val difference = p1 - p2
println("Difference: $difference") // Output: Difference: Point(x=5, y=5)
}
Real-world Application: Simple Calculator
Let's create a simple calculator application that uses various operators.
fun main() {
println("Welcome to Simple Calculator")
println("Enter first number:")
val num1 = readLine()?.toDoubleOrNull() ?: 0.0
println("Enter operation (+, -, *, /, %):")
val operation = readLine() ?: "+"
println("Enter second number:")
val num2 = readLine()?.toDoubleOrNull() ?: 0.0
val result = when(operation) {
"+" -> num1 + num2
"-" -> num1 - num2
"*" -> num1 * num2
"/" -> if (num2 != 0.0) num1 / num2 else "Error: Division by zero"
"%" -> if (num2 != 0.0) num1 % num2 else "Error: Division by zero"
else -> "Invalid operation"
}
println("Result: $result")
}
Summary
In this comprehensive guide to Kotlin operators, we've covered:
- Arithmetic operators for mathematical calculations
- Assignment operators for setting variable values
- Comparison operators for comparing values
- Logical operators for combining boolean expressions
- Bitwise operators for bit-level operations
- Range operators for creating and working with ranges
- Special Kotlin operators like Elvis, safe call, and not-null assertion
- Operator overloading for custom classes
- A practical application with a simple calculator
Understanding operators is essential for writing efficient Kotlin code, as they are the basic building blocks for more complex operations in your applications.
Exercises
To reinforce your learning, try these exercises:
- Create a temperature converter that converts between Celsius and Fahrenheit using arithmetic operators
- Write a function that checks if a number is within a certain range using range operators
- Create a custom
Money
class with overloaded operators for addition, subtraction, and comparison - Write a program that counts set bits in an integer using bitwise operators
- Implement a simple expression evaluator that can handle basic arithmetic operations
Additional Resources
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)