Operatory Kotlin: arytmetyka, operator przypisania i więcej

Kotlin ma zestaw operatorów do wykonywania operacji arytmetycznych, przypisywania, operatorów porównania i nie tylko. Z tego artykułu dowiesz się, jak korzystać z tych operatorów.

Operatory to specjalne symbole (znaki), które wykonują operacje na operandach (zmienne i wartości). Na przykład +jest operatorem wykonującym dodawanie.

W artykule o zmiennych Java nauczyłeś się deklarować zmienne i przypisywać wartości do zmiennych. Teraz nauczysz się, jak używać operatorów do wykonywania na nich różnych operacji.

1. Operatory arytmetyczne

Oto lista operatorów arytmetycznych w Kotlinie:

Operatory arytmetyczne Kotlina
Operator Znaczenie
+ Dodawanie (używane również do konkatenacji ciągów)
- Operator odejmowania
* Operator mnożenia
/ Operator dywizji
% Operator modułu

Przykład: operatory arytmetyczne

 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 uruchomieniu programu wynik będzie następujący:

 liczba1 + liczba2 = 16,0 liczba1 - liczba2 = 9,0 liczba1 * liczba2 = 43,75 liczba1 / liczba2 = 3,5714285714285716 liczba1% liczba2 = 2,0

+Operatora jest również stosowany do złączonych Stringwartości.

Przykład: konkatenacja ciągów

 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 uruchomieniu programu wynik będzie następujący:

Rozmowa jest tania. Pokaż mi kod. - Linus Torvalds

Jak właściwie działają operatory arytmetyczne?

Załóżmy, że używasz +operatora arytmetycznego, aby dodać dwie liczby a i b.

Pod maską wyrażenie a + bwywołuje a.plus(b)funkcję składową. plusOperator jest przeciążony do pracy z Stringwartości i innych podstawowych typów danych (z wyjątkiem Char logiczna).

 // + operator dla typów podstawowych 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 // dla konkatenacji ciągów operator fun String? .plus (other: Any?): String 

Możesz również użyć +operatora do pracy z typami zdefiniowanymi przez użytkownika (takimi jak obiekty) przez przeciążenie plus()funkcji.

Zalecana literatura: Przeciążanie operatora Kotlin

Oto tabela operatorów arytmetycznych i odpowiadających im funkcji:

Wyrażenie Nazwa funkcji Przetłumaczyć na
a + b plus a.plus (b)
a - b minus a. minus (b)
a * b czasy a. czasy (b)
a / b div a.div (b)
a% b mod a.mod (b)

2. Operatory przypisania

Operatory przypisania służą do przypisywania wartości zmiennej. Już wcześniej używaliśmy prostego operatora przypisania =.

 wiek = 5

Tutaj 5 jest przypisane do zmiennej wieku za pomocą =operatora.

Oto lista wszystkich operatorów przypisania i odpowiadających im funkcji:

Wyrażenie Równoważny Przetłumaczyć na
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)

Przykład: operatory przypisania

 fun main(args: Array) ( var number = 12 number *= 5 // number = number*5 println("number = $number") )

Po uruchomieniu programu wynik będzie następujący:

 liczba = 60

Zalecana lektura: Przeciążanie operatorów przypisań w Kotlin.

3. Jednoargumentowy prefiks i operatory zwiększania / zmniejszania

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

Oto kilka wyrażeń używających operatora invoke z odpowiednimi funkcjami w Kotlinie.

Wyrażenie Przetłumaczone na
a() a.invoke()
a(i) a.invoke(i)
a(i1, i2,… , in) a.inkove(i1, i2,… , in)
a(i) = b a.set(i, b)

W Kotlinie nawiasy są tłumaczone na wywołanie invokefunkcji składowej.

Zalecana lektura: Wywołaj przeciążenie operatora w Kotlin

Operacja bitowa

W przeciwieństwie do Javy w Kotlinie nie ma operatorów bitowych i bitowych. Do wykonania tego zadania wykorzystywane są różne funkcje (wspomagające notację wrostków):

  • shl - Podpisane przesunięcie w lewo
  • shr - Podpisana zmiana w prawo
  • ushr - Przesunięcie bez znaku w prawo
  • and - Bitowo i
  • or - bitowe lub
  • xor - Bitowe xor
  • inv - Inwersja bitowa

Odwiedź tę stronę, aby dowiedzieć się więcej o operacjach bitowych w Kotlinie.

Ponadto Kotlin nie ma operatora trójskładnikowego w przeciwieństwie do Javy.

Interesujące artykuły...