Operators
Prerequisites: Booleans and comparisons
An operator is a symbol that works on values, such as + or &&.
Arithmetic and assignment
+, -, *, /, %, plus compound assignment and increment:
fun main() {
var score = 10
score += 5
score -= 2
score *= 2
score++
println(score)
}
27
Logical operators
fun main() {
val age = 20
val hasTicket = true
println(age >= 18 && hasTicket)
println(age < 13 || age > 65)
println(!hasTicket)
}
true
false
false
&&(and) — true only if both sides are true.||(or) — true if either side is true.!(not) — flipstrueandfalse.
Kotlin stops as soon as the answer is known: in a && b, if a is
false, b is never evaluated.
The in operator
in checks membership — in a range, a collection, or a string:
fun main() {
val age = 42
println(age in 18..65)
println("b" in listOf("a", "b"))
println(7 !in 1..5)
}
true
true
true
No ternary operator
Kotlin has no condition ? a : b. Because if is an expression, you
write if (condition) a else b — covered in the Conditionals lesson.
Practice
A shop gives free delivery if an order is over 50 or the customer is a
member. With total = 42 and isMember = true, print whether delivery
is free.
Show solution
fun main() {
val total = 42
val isMember = true
println(total > 50 || isMember)
}
true