Kotlin Operators
An operator is a sign that compares values or combines truth values. A comparison gives true or false as its result.
Comparing numbers
Each comparison gives true or false. The printed answers show each result in order.
fun main() {
println(7 > 3)
println(7 < 3)
println(7 == 7)
}Equal strings
Two strings with the same letters are equal. A different spelling gives a different answer.
fun main() {
println("apple" == "apple")
println("apple" == "apply")
println("apple" != "apply")
}Both sides with &&
The && sign needs both sides to be true. One false side makes the whole result false.
fun main() {
val sunny = true
val warm = false
println(sunny && warm)
println(sunny && true)
}At least one side with ||
The || sign needs only one true side. It gives false only when both sides are false.
fun main() {
val sunny = true
val warm = false
println(sunny || warm)
println(warm || false)
}Flipping with !
The ! sign flips a Boolean value. True becomes false and false becomes true.
fun main() {
val ready = false
println(!ready)
println(ready)
}Example
fun main() {
val score = 75
val passed = score >= 50
println(passed)
println(passed && score < 100)
println(!passed || score == 75)
}Key points
- ==: checks whether two values are equal.
- !=: checks whether two values are different.
- < and >: compare size between two values.
- <= and >=: compare size and allow equality.
- &&: gives true only when both sides are true.
- ||: gives true when at least one side is true.
- !: flips true to false and false to true.
In this example, score holds 75. passed holds true because score >= 50 is true. The first print shows true. The second print joins passed with score < 100 and shows true. The third print flips passed and joins it with score == 75, and the right side makes the result true.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Kotlin Playground
Exercise
What does println(5 <= 5) print?