Kotlin Operators
Kotlin supports a wide range of operators for performing arithmetic, logical, comparison, and other operations. Here are some of the most commonly used operators in Kotlin:
Arithmetic operators: Kotlin supports the standard arithmetic operators
+
,-
,*
,/
, and%
for addition, subtraction, multiplication, division, and modulus (remainder), respectively.Assignment operators: Kotlin supports compound assignment operators such as
+=
,-=
,*=
,/=
, and%=
to modify a variable's value in-place.Comparison operators: Kotlin supports the standard comparison operators
==
,!=
,<
,>
,<=
, and>=
for comparing values.Logical operators: Kotlin supports the logical operators
&&
(AND),||
(OR), and!
(NOT) for combining and negating boolean expressions.Bitwise operators: Kotlin supports bitwise operators such as
and
,or
,xor
,shl
, andshr
for performing bitwise operations on integer values.Range operator: Kotlin has a range operator
..
for defining a range of values between two endpoints.
Here's an example that demonstrates the use of some of these operators:
fun main() { var x = 10 var y = 5 // Arithmetic operators println("x + y = ${x + y}") println("x - y = ${x - y}") println("x * y = ${x * y}") println("x / y = ${x / y}") println("x % y = ${x % y}") // Assignment operators x += 5 y *= 2 println("x = $x") println("y = $y") // Comparison operators val isGreater = x > y val isEqual = x == y println("isGreater = $isGreater") println("isEqual = $isEqual") // Logical operators val isTrue = true val isFalse = false println("isTrue && isFalse = ${isTrue && isFalse}") println("isTrue || isFalse = ${isTrue || isFalse}") println("!isTrue = ${!isTrue}") // Range operator val numbers = 1..10 println("Numbers between 1 and 10: ${numbers.joinToString()}") }
In this program, we use different operators to perform arithmetic, comparison, and logical operations. We also demonstrate the use of the range operator to define a range of integer values between 1 and 10.