When learning Kotlin for Android development, understanding variables is only the beginning.
Once we know how to store values using val and var, the next step is learning how to perform operations on those values.
For example, an Android application may need to:
- Calculate the total price of shopping cart items.
- Compare two numbers.
- Check whether a user is eligible for a feature.
- Validate multiple conditions.
- Increase or decrease a counter.
- Calculate discounts and percentages.
- Determine whether a button should be enabled.
Kotlin provides operators to perform these tasks.
In this tutorial, we’ll explore Kotlin arithmetic, comparison, logical, assignment, increment, decrement, range, and other useful operators with practical examples.
We’ll also see how operators work in modern Android applications using Jetpack Compose.
What You’ll Learn
By the end of this tutorial, you’ll understand:
- What Kotlin operators are
- Arithmetic operators
- Assignment operators
- Comparison operators
- Equality operators
- Logical operators
- Increment and decrement operators
- Range operators
- The
inand!inoperators - Operator precedence
- Integer division and remainder
- Kotlin operators in Jetpack Compose
- Common beginner mistakes
- Practical Kotlin exercises
Let’s begin!
1. What Are Operators in Kotlin?
Operators are symbols or keywords used to perform operations on values and variables.
For example:
val firstNumber = 10
val secondNumber = 20
val total = firstNumber + secondNumber
println(total)
Output:
30
Here:
firstNumbercontains 10.secondNumbercontains 20.+is the addition operator.totalstores the result.
Kotlin provides different categories of operators for different purposes.
2. Types of Operators in Kotlin
The most commonly used Kotlin operators include:
| Operator Category | Examples | ||
|---|---|---|---|
| Arithmetic | +, -, *, /, % | ||
| Assignment | =, +=, -=, *=, /=, %= | ||
| Comparison | >, <, >=, <= | ||
| Equality | ==, !=, ===, !== | ||
| Logical | &&, ` | , !` | |
| Increment / Decrement | ++, -- | ||
| Range and membership | .., ..<, in, !in |
We’ll explore each category with examples.
3. Kotlin Arithmetic Operators
Arithmetic operators are used to perform mathematical calculations.
Kotlin supports five basic arithmetic operators.
| Operator | Description | Example |
|---|---|---|
+ | Addition | 10 + 5 |
- | Subtraction | 10 - 5 |
* | Multiplication | 10 * 5 |
/ | Division | 10 / 5 |
% | Remainder | 10 % 3 |
Complete Example
fun main() {
val a = 20
val b = 6
println("Addition: ${a + b}")
println("Subtraction: ${a - b}")
println("Multiplication: ${a * b}")
println("Division: ${a / b}")
println("Remainder: ${a % b}")
}
Output:
Addition: 26
Subtraction: 14
Multiplication: 120
Division: 3
Remainder: 2
Notice that dividing two integers produces an integer result.
Let’s understand why.
4. Integer Division vs Decimal Division
One common beginner mistake is expecting decimal results when dividing integers.
Example
val result = 10 / 3
println(result)
Output:
3
Kotlin performs integer division because both operands are integers.
The fractional portion is discarded.
Decimal Division
To get a decimal result, use floating-point values.
val result = 10.0 / 3
println(result)
Output:
3.3333333333333335
You can also convert an integer to Double.
val a = 10
val b = 3
val result = a.toDouble() / b
println(result)
Best Practice
When your calculation requires fractional results, make sure the operands use appropriate numeric types.
For financial applications, consider decimal arithmetic rather than relying on floating-point precision.
5. Kotlin Remainder Operator (%)
The % operator returns the remainder after division.
Example
val result = 10 % 3
println(result)
Output:
1
The remainder operator is commonly used for checking even and odd numbers.
Even or Odd Example
fun main() {
val number = 12
if (number % 2 == 0) {
println("Even Number")
} else {
println("Odd Number")
}
}
Output:
Even Number
This is a practical example of combining arithmetic and comparison operators.
6. Kotlin Assignment Operators
Assignment operators are used to assign or update variable values.
The basic assignment operator is:
=
Example
var score = 100
Kotlin also provides compound assignment operators.
| Operator | Meaning | Example |
|---|---|---|
= | Assign value | a = 10 |
+= | Add and assign | a += 5 |
-= | Subtract and assign | a -= 5 |
*= | Multiply and assign | a *= 2 |
/= | Divide and assign | a /= 2 |
%= | Remainder and assign | a %= 3 |
Example
fun main() {
var score = 100
score += 20
println(score)
score -= 10
println(score)
score *= 2
println(score)
score /= 5
println(score)
}
Output:
120
110
220
44
Compound assignment operators help keep code concise.
Instead of:
score = score + 10
You can write:
score += 10
7. Kotlin Comparison Operators
Comparison operators compare two values and produce a Boolean result.
The result is either:
true
false
Comparison Operators
| Operator | Description |
|---|---|
> | Greater than |
< | Less than |
>= | Greater than or equal to |
<= | Less than or equal to |
Example
fun main() {
val a = 20
val b = 10
println(a > b)
println(a < b)
println(a >= b)
println(a <= b)
}
Output:
true
false
true
false
Practical Example: Age Eligibility
val age = 21
val isEligible = age >= 18
println(isEligible)
Output:
true
Comparison operators are frequently used in validation and conditional logic.
8. Kotlin Equality Operators
Equality operators are used to compare values.
Kotlin supports structural equality and referential equality.
Structural Equality
The == operator compares values using structural equality.
val firstName = "Alex"
val secondName = "Alex"
println(firstName == secondName)
Output:
true
The != operator checks whether values are not structurally equal.
println(10 != 20)
Output:
true
Referential Equality
Kotlin also provides:
===
!==
These check whether references point to the same object or different objects.
For example:
val first = mutableListOf(1, 2, 3)
val second = first
val third = mutableListOf(1, 2, 3)
println(first === second)
println(first === third)
Output:
true
false
For most ordinary value comparisons, use == and !=.
9. Kotlin Logical Operators
Logical operators combine or reverse Boolean conditions.
Kotlin provides three primary logical operators.
| Operator | Name | Description | ||
|---|---|---|---|---|
&& | Logical AND | True when both conditions are true | ||
| ` | ` | Logical OR | True when at least one condition is true | |
! | Logical NOT | Reverses a Boolean value |
Let’s explore each operator.
10. Logical AND Operator (&&)
The AND operator returns true only when both conditions are true.
Example
val age = 25
val hasLicense = true
val canDrive = age >= 18 && hasLicense
println(canDrive)
Output:
true
AND Truth Table
| Condition A | Condition B | Result |
|---|---|---|
| true | true | true |
| true | false | false |
| false | true | false |
| false | false | false |
Android Example
Suppose a feature requires the user to be logged in and have a premium subscription.
val isLoggedIn = true
val isPremium = true
val canAccessFeature = isLoggedIn && isPremium
println(canAccessFeature)
Output:
true
11. Logical OR Operator (||)
The OR operator returns true when at least one condition is true.
Example
val isAdmin = false
val isModerator = true
val canManageContent = isAdmin || isModerator
println(canManageContent)
Output:
true
OR Truth Table
| Condition A | Condition B | Result |
|---|---|---|
| true | true | true |
| true | false | true |
| false | true | true |
| false | false | false |
Logical OR is useful when multiple conditions can independently allow an operation.
12. Logical NOT Operator (!)
The NOT operator reverses a Boolean value.
Example
val isLoading = false
println(!isLoading)
Output:
true
Practical Example
val isUserLoggedIn = false
if (!isUserLoggedIn) {
println("Please log in")
}
Output:
Please log in
The NOT operator is frequently used for checking negative conditions.
13. Short-Circuit Evaluation in Kotlin
Kotlin’s logical AND and OR operators use short-circuit evaluation.
This means the second condition may not be evaluated if the first condition already determines the result.
Example with AND
val isLoggedIn = false
if (isLoggedIn && checkPremiumAccess()) {
println("Access granted")
}
Because isLoggedIn is false, Kotlin does not need to call checkPremiumAccess().
Example with OR
val isAdmin = true
if (isAdmin || checkModeratorAccess()) {
println("Access granted")
}
Because isAdmin is true, the second function isn’t evaluated.
This behavior can improve efficiency and help avoid unnecessary operations.
14. Increment and Decrement Operators
Kotlin provides operators to increase or decrease a variable by one.
Increment Operator
++
Decrement Operator
--
Example
var counter = 0
counter++
println(counter)
Output:
1
Decrement Example
var counter = 10
counter--
println(counter)
Output:
9
These operators are commonly used for counters and loops.
15. Prefix vs Postfix Increment
Kotlin supports prefix and postfix increment operators.
Prefix Increment
++counter
The variable is incremented before the expression produces its value.
Postfix Increment
counter++
The expression produces the previous value before incrementing the variable.
Example
var a = 5
val first = ++a
println(first)
println(a)
Output:
6
6
Postfix Example
var b = 5
val second = b++
println(second)
println(b)
Output:
5
6
Understanding this distinction is useful when working with expressions and loops.
16. Kotlin Range Operators
Kotlin provides convenient syntax for representing ranges.
Inclusive Range
1..5
This represents values from 1 through 5.
Example
for (number in 1..5) {
println(number)
}
Output:
1
2
3
4
5
Half-Open Range
Kotlin also supports:
1..<5
This includes 1 but excludes 5.
Example
for (number in 1..<5) {
println(number)
}
Output:
1
2
3
4
The ..< syntax is available in modern Kotlin versions.
17. Kotlin in and !in Operators
The in operator checks whether a value belongs to a range or collection.
Example
val age = 20
println(age in 18..60)
Output:
true
Using !in
The !in operator checks whether a value is not contained in a range or collection.
val number = 15
println(number !in 1..10)
Output:
true
Practical Example
val score = 85
if (score in 80..100) {
println("Excellent Score")
}
Output:
Excellent Score
These operators make validation logic more readable.
18. Kotlin Operator Precedence
Operator precedence determines the order in which operations are evaluated.
Example
val result = 10 + 5 * 2
println(result)
Output:
20
Multiplication is evaluated before addition.
Using Parentheses
val result = (10 + 5) * 2
println(result)
Output:
30
Parentheses help make calculations explicit.
Common Precedence Rules
For the operators covered here:
- Parenthesized expressions are evaluated first.
- Multiplication, division, and remainder bind more tightly than addition and subtraction.
- Arithmetic expressions are evaluated before ordinary numeric comparisons.
- Logical AND binds more tightly than logical OR.
When expressions become complex, use parentheses to improve readability.
19. Kotlin Elvis Operator (?:)
Kotlin provides the Elvis operator for handling nullable values.
The Elvis operator is:
?:
It returns the left-hand value when that value is not null; otherwise, it evaluates and returns the right-hand expression.
Example
val username: String? = null
val displayName = username ?: "Guest"
println(displayName)
Output:
Guest
Practical Android Example
val profileName: String? = null
val title = profileName ?: "Welcome User"
println(title)
Output:
Welcome User
The Elvis operator is useful when working with optional data.
We’ll explore Kotlin null safety in more detail in a future article.
20. Kotlin Operators in Android Development
Operators are used in almost every Android application.
For example:
- Shopping cart calculations
- Form validation
- Authentication checks
- Progress tracking
- Game scoring
- Button enable/disable conditions
- UI state calculations
Let’s explore a simple Android example.
Shopping Cart Calculation
val itemPrice = 250
val quantity = 3
val deliveryFee = 40
val total = itemPrice * quantity + deliveryFee
println("Total Amount: ₹$total")
Output:
Total Amount: ₹790
This example combines multiplication and addition.
21. Kotlin Operators in Jetpack Compose
Let’s create a simple counter application using Kotlin operators.
Complete Example
@Composable
fun CounterOperatorScreen() {
var counter by remember {
mutableIntStateOf(0)
}
Column(
modifier = Modifier
.fillMaxSize()
.padding(24.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = "Kotlin Operators Demo",
style = MaterialTheme.typography.headlineMedium
)
Spacer(
modifier = Modifier.height(20.dp)
)
Text(
text = "Counter: $counter",
style = MaterialTheme.typography.headlineSmall
)
Spacer(
modifier = Modifier.height(24.dp)
)
Row(
horizontalArrangement = Arrangement.spacedBy(12.dp)
) {
Button(
onClick = {
counter--
},
enabled = counter > 0
) {
Text("-")
}
Button(
onClick = {
counter++
},
enabled = counter < 10
) {
Text("+")
}
}
Spacer(
modifier = Modifier.height(16.dp)
)
Text(
text = if (counter >= 5) {
"Counter is 5 or greater"
} else {
"Counter is below 5"
}
)
}
}
Required Imports
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
Expected UI
+--------------------------------+
| |
| Kotlin Operators Demo |
| |
| Counter: 0 |
| |
| [-] [+] |
| |
| Counter is below 5 |
| |
+--------------------------------+
How It Works
This example demonstrates several Kotlin operators.
Increment:
counter++
Increases the counter.
Decrement:
counter--
Decreases the counter.
Greater than:
counter > 0
Enables the decrement button only when the counter is greater than zero.
Less than:
counter < 10
Enables the increment button only when the counter is below ten.
Greater than or equal to:
counter >= 5
Determines which message appears.
Jetpack Compose automatically updates the relevant UI when the observable counter state changes.
22. Common Kotlin Operator Mistakes
Mistake 1: Confusing = and ==
The = operator assigns a value.
var age = 20
The == operator compares values.
println(age == 20)
Don’t confuse assignment with comparison.
Mistake 2: Expecting Decimal Results from Integer Division
val result = 5 / 2
Output:
2
For decimal results:
val result = 5.0 / 2
Output:
2.5
Mistake 3: Using && Instead of ||
Suppose access should be allowed when a user is an admin OR a moderator.
Correct:
isAdmin || isModerator
Using && would require both conditions to be true.
Mistake 4: Forgetting Parentheses
Complex expressions can be difficult to understand.
Prefer:
val result = (price + tax) * quantity
when parentheses clarify the intended calculation.
Mistake 5: Modifying a val
Incorrect:
val counter = 0
counter++
Correct:
var counter = 0
counter++
Mistake 6: Dividing by Zero
Integer division by zero throws an ArithmeticException.
Avoid unsafe calculations.
val divisor = 0
if (divisor != 0) {
println(10 / divisor)
} else {
println("Cannot divide by zero")
}
23. Kotlin Operators Quick Reference
| Operator | Description | Example | ||||
|---|---|---|---|---|---|---|
+ | Addition | 10 + 5 | ||||
- | Subtraction | 10 - 5 | ||||
* | Multiplication | 10 * 5 | ||||
/ | Division | 10 / 5 | ||||
% | Remainder | 10 % 3 | ||||
= | Assignment | a = 10 | ||||
+= | Add and assign | a += 5 | ||||
== | Structural equality | a == b | ||||
!= | Structural inequality | a != b | ||||
> | Greater than | a > b | ||||
< | Less than | a < b | ||||
>= | Greater or equal | a >= b | ||||
<= | Less or equal | a <= b | ||||
&& | Logical AND | a && b | ||||
| ` | ` | Logical OR | `a | b` | ||
! | Logical NOT | !a | ||||
++ | Increment | counter++ | ||||
-- | Decrement | counter-- | ||||
.. | Inclusive range | 1..10 | ||||
..< | Half-open range | 1..<10 | ||||
in | Membership | 5 in 1..10 | ||||
!in | Not a member | 15 !in 1..10 | ||||
?: | Elvis operator | name ?: "Guest" |
24. Practical Exercises
Try these exercises in Kotlin or Android Studio.
Exercise 1: Basic Calculator
Create two variables:
val a = 20
val b = 5
Print:
- Addition
- Subtraction
- Multiplication
- Division
- Remainder
Exercise 2: Even or Odd
Create a Kotlin program that checks whether a number is even or odd.
Hint:
number % 2 == 0
Exercise 3: Login Validation
Create two Boolean variables:
val isLoggedIn = true
val isVerified = false
Check whether both conditions are true.
Exercise 4: Age Range Validation
Create an age variable.
Check whether the age is between 18 and 60 using in.
Exercise 5: Jetpack Compose Counter
Create a counter screen with:
- Increment button
- Decrement button
- Minimum value of 0
- Maximum value of 10
- Dynamic message based on the counter value
What We’ve Learned
In this tutorial, we learned:
- What Kotlin operators are
- Arithmetic operators
- Integer and decimal division
- Remainder operator
- Assignment operators
- Comparison operators
- Structural and referential equality
- Logical AND, OR, and NOT
- Short-circuit evaluation
- Increment and decrement
- Prefix and postfix operators
- Range and membership operators
- Operator precedence
- Elvis operator
- Using operators in Android applications
- Practical Jetpack Compose examples
- Common beginner mistakes
Kotlin operators are essential for calculations, validation, conditional logic, and state updates in Android applications.
As you continue learning Kotlin, you’ll use these operators regularly when building real-world Android features.
What’s Next?
In our next tutorial, we’ll explore:
Kotlin If Else and When Expressions Explained with Examples
You’ll learn:
- Kotlin
ifstatements if-elseconditionselse ifchainsifas an expression- Kotlin
whenexpressions - Multiple conditions
whenwith ranges- Practical Android examples
- Conditional UI rendering in Jetpack Compose
Happy Coding!
Continue learning modern Android development with Moiks Developer Blog.