Kotlin Operators
Operators let you combine values to perform arithmetic, compare data, and build logical conditions.
Arithmetic Operators
Kotlin supports the standard arithmetic operators +, -, *, /, and % (remainder), which work on all numeric types. Division between two integers truncates toward zero, so understanding the operand types matters as much as the operator itself.
Arithmetic operators with Int
fun main() {
val a = 17
val b = 5
println("Sum: ${a + b}")
println("Difference: ${a - b}")
println("Product: ${a * b}")
println("Integer division: ${a / b}")
println("Remainder: ${a % b}")
}Comparison Operators
Comparison operators (==, !=, <, >, <=, >=) evaluate to a Boolean. Unlike Java, Kotlin's == calls the equals() method for objects, so it checks structural equality rather than reference identity by default; use === to compare references directly.
Comparison operators
fun main() {
val x = 10
val y = 20
println(x == y) // false
println(x != y) // true
println(x < y) // true
println(x >= y) // false
val name1 = "Kotlin"
val name2 = "Kotlin"
println(name1 == name2) // true, structural equality
}Logical Operators
Logical operators combine Boolean expressions: && (AND) is true only when both sides are true, || (OR) is true when at least one side is true, and ! negates a Boolean. Kotlin evaluates && and || lazily, so the right-hand side is skipped once the result is already determined.
- Arithmetic operators (*, /, %) bind tighter than + and -
- Comparison operators are evaluated after arithmetic operators
- && binds tighter than ||, so a || b && c means a || (b && c)
- Use parentheses whenever precedence is not immediately obvious to a reader
Combining comparisons with logical operators
fun main() {
val age = 25
val hasLicense = true
val canDrive = age >= 18 && hasLicense
val needsSupervision = age < 18 || !hasLicense
println("Can drive alone: $canDrive")
println("Needs supervision: $needsSupervision")
}Exercise: Kotlin Operators
What does 7 / 2 evaluate to when both operands are Int?