Kotlin má množinu operátorov na vykonávanie aritmetických operácií, operácií priraďovania, porovnávania a ďalších. V tomto článku sa naučíte používať tieto operátory.
Operátory sú špeciálne symboly (znaky), ktoré vykonávajú operácie s operandmi (premennými a hodnotami). Napríklad +je operátor, ktorý vykonáva sčítanie.
V článku Premenné Java ste sa naučili deklarovať premenné a priraďovať hodnoty premenným. Teraz sa naučíte používať operátory na vykonávanie rôznych operácií.
1. Aritmetické operátory
Tu je zoznam aritmetických operátorov v Kotline:
Kotlinské aritmetické operátory| Prevádzkovateľ | Význam |
|---|---|
| + | Sčítanie (tiež sa používa na zreťazenie reťazcov) |
| - | Operátor odčítania |
| * | Operátor násobenia |
| / | Operátor divízie |
| % | Prevádzkovateľ modulu |
Príklad: Aritmetické operátory
fun main(args: Array) ( val number1 = 12.5 val number2 = 3.5 var result: Double result = number1 + number2 println("number1 + number2 = $result") result = number1 - number2 println("number1 - number2 = $result") result = number1 * number2 println("number1 * number2 = $result") result = number1 / number2 println("number1 / number2 = $result") result = number1 % number2 println("number1 % number2 = $result") )
Po spustení programu bude výstup:
number1 + number2 = 16,0 number1 - number2 = 9,0 number1 * number2 = 43,75 number1 / number2 = 3,5714285714285716 number1% number2 = 2,0
+Operátor sa používa aj pre zreťazenie Stringhodnôt.
Príklad: zreťazenie reťazcov
fun main(args: Array) ( val start = "Talk is cheap. " val middle = "Show me the code. " val end = "- Linus Torvalds" val result = start + middle + end println(result) )
Po spustení programu bude výstup:
Hovor je lacný. Ukáž mi kód. - Linus Torvalds
Ako vlastne fungujú aritmetické operátory?
Predpokladajme, že +na pridanie dvoch čísel a a b používate aritmetický operátor.
Pod kapotou výraz a + bvolá a.plus(b)funkciu člena. plusOperátor je preťažený na prácu s Stringhodnotami a ďalších základných dátových typov (s výnimkou Char a Boolean).
// + operátor pre základné typy operator fun plus (other: Byte): Int operator fun plus (other: Short): Int operator fun plus (other: Int): Int operator fun plus (other: Long): Long operator fun plus (other: Float): Float operator fun plus (other: Double): Double // for string concatenation operator fun String? .plus (other: Any?): String
+Operátor môžete tiež použiť na prácu s používateľsky definovanými typmi (napríklad objektmi) plus()funkciou preťaženia .
Odporúčame prečítať : Preťaženie operátora Kotlin
Tu je tabuľka aritmetických operátorov a ich zodpovedajúcich funkcií:
| Vyjadrenie | Názov funkcie | Prekladá do |
|---|---|---|
| a + b | plus | a.plus (b) |
| a - b | mínus | a.minus (b) |
| a * b | krát | a.krát (b) |
| a / b | div | a.div (b) |
| a% b | mod | a.mod (b) |
2. Prevádzkovatelia priradenia
Na priradenie hodnoty premennej sa používajú operátory priradenia. Jednoduchý operátor priradenia sme už predtým používali =.
vek val = 5
Tu je pomocou =operátora priradený 5 k variabilnému veku .
Tu je zoznam všetkých operátorov priradenia a ich zodpovedajúcich funkcií:
| Vyjadrenie | Rovná sa | Prekladá do |
|---|---|---|
| a + = b | a = a + b | a.plusAssign (b) |
| a - = b | a = a - b | a.minusAssign (b) |
| a * = b | a = a * b | a.timesAssign (b) |
| a / = b | a = a / b | a.divAssign (b) |
| a% = b | a = a% b | a.modAssign (b) |
Príklad: Prevádzkovatelia priradenia
fun main(args: Array) ( var number = 12 number *= 5 // number = number*5 println("number = $number") )
Po spustení programu bude výstup:
číslo = 60
Odporúčame prečítať: Preťaženie operátorov priradenia v Kotline.
3. Unárna predpona a operátory prírastku / zníženia
Here's a table of unary operators, their meaning, and corresponding functions:
| Operator | Meaning | Expression | Translates to |
|---|---|---|---|
| + | Unary plus | +a | a.unaryPlus() |
| - | Unary minus (inverts sign) | -a | a.unaryMinus() |
| ! | not (inverts value) | !a | a.not() |
| ++ | Increment: increases value by1 | ++a | a.inc() |
| -- | Decrement: decreases value by 1 | --a | a.dec() |
Example: Unary Operators
fun main(args: Array) ( val a = 1 val b = true var c = 1 var result: Int var booleanResult: Boolean result = -a println("-a = $result") booleanResult = !b println("!b = $booleanResult") --c println("--c = $c") )
When you run the program, the output will be:
-a = -1 !b = false --c = 0
Recommended Reading: Overloading Unary Operators
4. Comparison and Equality Operators
Here's a table of equality and comparison operators, their meaning, and corresponding functions:
| Operator | Meaning | Expression | Translates to |
|---|---|---|---|
| > | greater than | a> b | a.compareTo(b)> 0 |
| < | less than | a < b | a.compareTo(b) < 0 |
| >= | greater than or equals to | a>= b | a.compareTo(b)>= 0 |
| <= | less than or equals to | a < = b | a.compareTo(b) <= 0 |
| == | is equal to | a == b | a?.equals(b) ?: (b === null) |
| != | not equal to | a != b | !(a?.equals(b) ?: (b === null)) |
Comparison and equality operators are used in control flow such as if expression , when expression , and loops .
Example: Comparison and Equality Operators
fun main(args: Array) ( val a = -12 val b = 12 // use of greater than operator val max = if (a> b) ( println("a is larger than b.") a ) else ( println("b is larger than a.") b ) println("max = $max") )
When you run the program, the output will be:
b is larger than a. max = 12
Recommended Reading: Overloading of Comparison and Equality Operators in Kotlin
5. Logical Operators
There are two logical operators in Kotlin: || and &&
Here's a table of logical operators, their meaning, and corresponding functions.
| Operator | Description | Expression | Corresponding Function |
|---|---|---|---|
| || | true if either of the Boolean expression is true | (a>b)||(a | (a>b)or(a |
| && | true if all Boolean expressions are true | (a>b)&&(a | (a>b)and(a |
Note that, or and and are functions that support infix notation.
Logical operators are used in control flow such as if expression , when expression , and loops .
Example: Logical Operators
fun main(args: Array) ( val a = 10 val b = 9 val c = -1 val result: Boolean // result is true is a is largest result = (a>b) && (a>c) // result = (a>b) and (a>c) println(result) )
When you run the program, the output will be:
true
Recommended Reading: Overloading of Logical Operators in Kotlin
6. in Operator
The in operator is used to check whether an object belongs to a collection.
| Operator | Expression | Translates to |
|---|---|---|
| in | a in b | b.contains(a) |
| !in | a !in b | !b.contains(a) |
Example: in Operator
fun main(args: Array) ( val numbers = intArrayOf(1, 4, 42, -3) if (4 in numbers) ( println("numbers array contains 4.") ) )
When you run the program, the output will be:
numbers array contains 4.
Recommended Reading: Kotlin in Operator Overloading
7. Index access Operator
Here are some expressions using index access operator with corresponding functions in Kotlin.
| Expression | Translated to |
|---|---|
a(i) | a.get(i) |
a(i, n) | a.get(i, n) |
a(i1, i2,… , in) | a.get(i1, i2,… , in) |
a(i) = b | a.set(i, b) |
a(i, n) = b | a.set(i, n, b) |
a(i1, i2,… , in) = b | a.set(i1, i2,… , in, b) |
Example: Index access Operator
fun main(args: Array) ( val a = intArrayOf(1, 2, 3, 4, - 1) println(a(1)) a(1)= 12 println(a(1)) )
When you run the program, the output will be:
2 12
Recommended Reading: Kotlin Index access operator Overloading
8. Invoke Operator
Tu je niekoľko výrazov používajúcich operátor invoke s príslušnými funkciami v Kotline.
| Vyjadrenie | Preložené do |
|---|---|
a() | a.invoke() |
a(i) | a.invoke(i) |
a(i1, i2,… , in) | a.inkove(i1, i2,… , in) |
a(i) = b | a.set(i, b) |
V Kotline sa zátvorky prekladajú do funkcie volania invokečlena.
Odporúčame prečítať: Vyvolajte preťaženie operátora v Kotline
Bitová operácia
Na rozdiel od Javy neexistujú v Kotline bitové a bitové operátory. Na vykonanie tejto úlohy sa používajú rôzne funkcie (podporujúce notáciu infix):
shl- Podpísaný posun vľavoshr- Podpísaný posun dopravaushr- Nepodpísané radenie vpravoand- Bitové aor- Bitové aleboxor- Bitový xorinv- Bitová inverzia
Navštívte túto stránku a dozviete sa viac o bitových operáciách v Kotline.
Na rozdiel od Javy tiež v Kotline neexistuje ternárny operátor.








