List of relational operators
Kotlin provides six relational operators to work with numbers:
==— equal toX!=— not equal toX>— greater thanX>=— greater than or equal toX<— less thanX<=— less than or equal toX
A relational operator results in a Boolean value (true or false) regardless of the operand type.
Comparing integer numbers
Relational operators allow you to compare two integer numbers, among other things. Here are some examples:
val one = 1
val two = 2
val three = 3
val four = 4
val oneIsOne = one == one // true
val res1 = two <= three // true
val res2 = two != four // true
val res3 = two > four // false
val res4 = one == three // false
You can use relational operators together with arithmetic operators. In these expressions, relational operators have a lower priority than arithmetic operators.
Let's take a look at the example below. First, Kotlin calculates two sums, and after that, they are compared with the > operator:
val number = 1000
val result = number + 10 > number + 9 // 1010 > 1009 is true
The result is true.
Note that you cannot check the equality of Int and Long! You can compare Int and Long freely with >, <. >=, <=, but cannot use == and !=. You can check equality only for the same types, so you need to convert Int to Long:
val one: Long = 1
val zero: Int = 0
println(one >= zero) // OK, prints true
// println(one == zero) Error
println(one == zero.toLong()) // OK, prints falseJoining relational operations
Kotlin cannot process expressions like:
a <= b <= c
You should join two Boolean expressions using logical operators like || and && instead.
For example, let's say we need to check the validity of the following expression:
100 < number < 200
To do that, we should write something like this:
number > 100 && number < 200
Also, we can put different parts of the expression in the parentheses:
(number > 100) && (number < 200)
The parentheses are not necessary, though, as relational operators have a higher priority.
Logical operators allow you to join a sequence of relational operations in a single expression. This is a widely used trick in programming.
As a more complex example, let's write a program that reads an integer number and checks whether a number belongs to the following range — [100; 200] including 100 and 200:
fun main() {
val left = 100
val right = 200
val number = readln().toInt()
val inRange = number >= left && number <= right // joining two expressions using AND
println(inRange)
}
You can have something like this:
50 results in
false99 results in
false100 results in
true200 results in
true, and so on.
Conclusion
In this topic, we discussed a couple of very useful relational operators — ==, !=, >, >=, <, and <=. You can construct difficult statements by joining them with logical operators. But remember, they will always result in a Boolean value. Further on, we will show you how you can implement these operators in your programs in Kotlin.