Kotlin-operatører: Aritmetikk, Oppdragsoperatør og mer

Kotlin har et sett med operatører for å utføre regning, oppdrag, sammenligningsoperatører og mer. Du vil lære å bruke disse operatørene i denne artikkelen.

Operatører er spesielle symboler (tegn) som utfører operasjoner på operander (variabler og verdier). For eksempel +er en operatør som utfører tillegg.

I artikkelen om Java-variabler lærte du å erklære variabler og tilordne verdier til variabler. Nå vil du lære å bruke operatører til å utføre forskjellige operasjoner på dem.

1. Aritmetiske operatører

Her er en liste over regneoperatører i Kotlin:

Kotlin aritmetiske operatører
Operatør Betydning
+ Tillegg (brukes også til strengkonkatenering)
- Subtraksjonsoperatør
* Multiplikasjonsoperatør
/ Divisjonsoperatør
% Moduloperatør

Eksempel: Aritmetiske operatører

 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") ) 

Når du kjører programmet, vil utdataene være:

 tall1 + nummer2 = 16,0 nummer1 - nummer2 = 9,0 nummer1 * nummer2 = 43,75 nummer1 / nummer2 = 3,5714285714285716 nummer1% nummer2 = 2,0

Den +operatør også brukes for sammenkjeding av Stringverdier.

Eksempel: Sammenkobling av strenger

 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) )

Når du kjører programmet, vil utdataene være:

Snakk er billig. Vis meg koden. - Linus Torvalds

Hvordan fungerer regneoperatører egentlig?

Anta at du bruker +regneoperatør for å legge til to tall a og b.

Under panseret a + bkaller uttrykket a.plus(b)medlemsfunksjon. Den plusoperatør er overbelastet for å arbeide med Stringverdier og andre grunnleggende datatyper (unntatt Char og boolsk).

 // + operator for grunnleggende typer operator moro pluss (annet: Byte): Int operator moro pluss (annet: Short): Int operator moro pluss (annet: Int): Int operator moro pluss (annet: Long): Long operator fun plus (annet: Float): Float operator fun plus (other: Double): Double // for string concatenation operator fun String? .plus (other: Any?): String 

Du kan også bruke +operatøren til å jobbe med brukerdefinerte typer (som objekter) ved å overbelaste plus()funksjonen.

Anbefalt lesing: Overbelastning av Kotlin-operatør

Her er en tabell over regneoperatører og deres tilhørende funksjoner:

Uttrykk Funksjonsnavn Oversetter til
a + b i tillegg til a.plus (b)
a - b minus a.minus (b)
a * b ganger a.tider (b)
a / b div a.div (b)
a% b mod a.mod (b)

2. Oppdragsoperatører

Oppdragsoperatører brukes til å tilordne verdi til en variabel. Vi har allerede brukt enkel oppdragsoperatør =før.

 val alder = 5

Her tildeles 5 variabel alder ved hjelp av =operator.

Her er en liste over alle oppdragsoperatører og deres tilhørende funksjoner:

Uttrykk Tilsvarende Oversetter til
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)

Eksempel: Oppdragsoperatører

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

Når du kjører programmet, vil utdataene være:

 nummer = 60

Anbefalt lesing: Overbelastning av oppdragsoperatører i Kotlin.

3. Unary prefiks og Increment / Decrement Operators

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

Her er noen uttrykk som bruker påkalle operatør med tilsvarende funksjoner i Kotlin.

Uttrykk Oversatt til
a() a.invoke()
a(i) a.invoke(i)
a(i1, i2,… , in) a.inkove(i1, i2,… , in)
a(i) = b a.set(i, b)

I Kotlin oversettes parenteser til å ringe invokemedlemsfunksjon.

Anbefalt lesing: Påkalle operatøroverbelastning i Kotlin

Bitvis drift

I motsetning til Java er det ingen bitvise og bitshift-operatører i Kotlin. For å utføre denne oppgaven brukes forskjellige funksjoner (støttende infiksnotasjon):

  • shl - Signert skift til venstre
  • shr - Signert skift til høyre
  • ushr Usignert skift til høyre
  • and - Bitvis og
  • or - Bitvis eller
  • xor - Bitvis xor
  • inv - Bitvis inversjon

Besøk denne siden for å lære mer om Bitwise-operasjoner i Kotlin.

Det er heller ingen ternær operatør i Kotlin i motsetning til Java.

Interessante artikler...