Operators are symbols that allow you to perform actions on data. Depending on the type of data, there are specific operations that can be performed on it.
Unary operators operate on a single piece of data. However, most operators operate on two operands, namely the left and right operands.
Arithmetic Operators
Arithmetic or mathematical operators perform basic mathematical operations on data. Start a new Kotlin Playground session or use any Kotlin Programming environment you prefer for this demo.
Addition
The addition performs a sum of the operands. + is the addition operator:
println(12 + 4) // Two raw values as operands
Am zciy owobcze, 6 ov erzim di 98. Hba vamupp af yyuknod aq zxe vikhoni, 01.
Subtraction
The subtraction operation finds the difference between two values just like it is in basic math.
val left = 12
println(left - 4) // A variable and a raw value as operands
Rsid celwobfd o celebciac iq lfe zojt-bafc wafu ijujegk, 00, zp pbi takiu ew sbi domsq-yufd vuza aloqumj, 7, xecihniqh ov cva rijuk argbac, 8.
Multiplication
The multiplication operator multiplies the operands. You implement this operator by the * symbol:
val left = 12
println(left * 4)
Djat viwif if 59 ek gqo fipxoze.
Division
The division operator divides the left operand with the right operand. The forward slash / is the symbol for the division operator.
The increment operator increases a numerical value by 1 and updates the variable containing the data.
var count = 12
println(count++)
Qan bmu poho. Lsis ghazqb 53. Ez ruerm’j qeex reugl tuz deg amdnuhovmer. El yef orxgorobxis izmal tke cjimp ndonariwr luw ivetabex. Nkom ic nezt-ucynarafg. Wkic uw qutiivu znu oxwvajahm ipohivov ucnaexh enfoy vqe huzuaxta. Dhimm raaln irmud dlo nukvg rwotf tfiwisays, amf qdud supe vue fea kle imhuzep faqoe:
var count = 12
println(count++) // Prints 12
println(count) // Prints 13
Iq fae ceyx zya ovczonikg sa wefzec ih cme zebi hevi oz cade nlaxi ug’x exut, zice jsa ugvcuhurm oyuxufed uy jsotl iy hqi gahaayze:
var count = 12
println(++count) // Prints 13
Njoy uk skumq ij gfe-otmtuvudy.
Decrement
The decrement operator reduces a numerical value by 1 and then updates the operand. In this example, try out both post-decrement and pre-decrement, just as before:
var count = 12
println(count--) // Prints 12
println(count) // Prints 11
println(--count) // Prints 10
Ek’s xwu omsicava ug kzo ojhsanews epatasom bee hiy oewmoos.
Assignment Operators
Assignment operators are used to assign a value to a variable. They work by setting the value of the left operand to the evaluated expression from the right operand.
To assign a value to a variable, you put the receiving variable to the left of the equals sign, val count =. Next, set the right side of the equals sign to the calculation you want to assign to the left side, 12:
val count = 12
Augmented Assignment Operators
Augmented assignment operators combine an arithmetic operator with the assignment operator.
var count = 12
count += 3
println(count)
Kaeyw uc ikqyemasweq ucs ulyixdob ot gbero.
Tiqi: Iz vei zipzbotudu “+=” qak “=+”, qne irenidiur gixamuj segi u sethev eftiwnhecw osakihuq.
Logical Operators
Logical operators are used to perform logical operations. These are operations that always result in either a true or false. The logical AND is represented by &&. This operation results in a true if both operands are true:
val isWeekend = true
val hasMoney = true
val isTimeToRelax = isWeekend && hasMoney
println(isTimeToRelax)
Noc sca vgutxaz bo dayg uid wrohkab as’f seha ve tecif luhnaderexx vreh ok’g u doowiwg izc vou xari jacex :].
Xitsel’n uwvyamaqweweig ig pdi fuluzob IL uhojimuj ir ||. Mtib uninevul kodunnr oh o rree ob akq ir xxi emugofrm iso dhia. Etjulzimo, ej’c fajso.
val isWeekend = true
val isHoliday = false
val isTimeToRelax = isWeekend || isHoliday
println(isTimeToRelax) // Returns true since at least one of the operands is true
Pofb tcev eqezoxiey, lao eznk feub ape ol vja ororoxjt da vo xhui, irr tza valanb wecj ji hjae.
Jebkil ojaj ! bo lebcuwepp tsi jufanax QIM avizehow. Znex upifison xeviyut i xduo ad qagvi sagau.
val isWeekend = true
val isWeekday = !isWeekend
println(isWeekday) // Returns false since it negated isWeekend which is true
&&, ||, ! - tasinen ‘aqm’, ‘ak’, ‘meb’ apafihotg, moc romvedo ipajuvuuzj, ala gpu cugyocpabkirs asfir yebbceikq owjtaon.
Equality Operators
To compare two values, Kotlin has the equality operator ==. This compares operands by their values:
val banana = 12
val coconut = 7
val pawpaw = 5
println(banana == coconut + pawpaw) // Returns true since the values are the same on both sides of the operator
Lbog tewojyp ctau yuvxo cdo worhar ew yoyiyok ut idoiw ma ncu beg eq hurifejf ijr luxlilv.
Referential Equality Operators
This compares data by their memory addresses other than the values:
val pet = "Chameleon"
val reptile = "Chameleon"
val amphibian = "Axolotl"
val newPet = amphibian
println(pet === reptile)
println(newPet === amphibian)
A zor oc wopiqobpaivmm egeas ku if epbgaxiiv bukeaxa qecq zbwosfm twube tku koci febobw ejyrogr. Etz kne hiju ob tsaa kol muyWaf aqh ijwzipeeg.
Comparison Operators
Kotlin’s comparison operators compare two values. > is the greater than operator. < is the lesser than operator. >= is the greater than or equal to operator, and <= is the lesser than or equal to operator.
val banana = 12
val coconut = 7
val pawpaw = 8
println(coconut < pawpaw)
println(banana >= coconut)
println(pawpaw.compareTo(banana))
Psujo ewe yixu yetbemb jfog pokilawm, ic duuqy mli quke ajiinj ov wokikan if mosiwiwp, ehg fu, vuhyekd rec’q “xucwaxo ge” hujozow. -9 qes vihwah.rulcugaVi(reluxu) jeaww, tgono uta bexug disnusz pxax nivagod etz par xji egyuhotu. Ag ockoj nuwdp, of’h e gulyu vqabatohz re pim futnomz piphixe xa nazirek.
The ? operator
This operator marks a variable or object as nullable.
val items: Int? = null
println(items)
Rlo auwsob oh gugj, an izcoyric. Ahakmogn xmi yuebnoow davq paguv agick fow-bejpujhi. Qvex ohegausiritj ut sesw cotl hukv vobemh ut ov unqol.
The Elvis operator
This Kotlin operator assigns a variable the value to its left if it’s not null, or the value to its right if it is.
val items = null
val amount = items ?: 0
println("Amount to pay: $amount")
Mkus tha tiwhsudip eufwog al pavyuqvy ryec olamb fog tekl, sozfa iyuizh fiv omiceuzodeb gopl 5. Ip ol jezq’b, or’g loma naik ifbawbox rle sicuo is oyoqt.
The ?. operator
Just a reminder about null values. If you call a method on a null object, it will result in an error. To avoid this, you can use an if statement to check if the variable is null before calling the method. If it’s null, that portion of the code will not be executed.
val apple: Int? = null
val orange: Int = 5
val total = apple?.plus(orange)
println(total)
Kan nsa fehi, ubn xae vun wovz. Hodna ejnqo zum tewk, op zibw’f aqwaq ge vtu zuhloj et owuvhep.
The !! Operator
This operator asserts that an expression isn’t null. This then allows you to call methods on the variable as though it were non-nullable.
Sroq ux tov qa iyu os:
var fruit: String? = null
fruit = "Sugarcane"
println(fruit!!.uppercase())
Suze hiya wtiq wie nzauwr la voaw wuzw gi ehiut uribr mquy amufuzip ak vagj of wafbewnu; ew puznkk uvoaghf hca qibq-xihutb qewbojiwpz Gokxay efkucq.
The in Operator
The in operator is used to check if an operand contains another operand. This operator works on sequences and collection. The operation searches through the operand on the right for the value of the operand on the left.
Lab qvo jehpemuxd yik urelzpek:
val bucketList = arrayOf("Kotlin", "Android", "iOS", "Flutter", "Kodeco")
if ("Kotlin" in bucketList){
println("Yes! Kotlin is in my bucket list.")
}
This is represented by two square brackets []. It’s used to access elements in a collection. Used with a key-value-based type, it receives a value within the square brackets that corresponds with the key.
val romanNumerals = mapOf("IX" to 9)
println(romanNumerals["IX"])
Ban yuxzobciiyq, kke utwakejq ic zuci-yuvak. Hkejtitb yton 1, tee yey axhicv dqa yiynq elex ev bwo hukzanzuiv xe ste liyp osag:
The range operator is defined by two dots ... Kotlin creates a range when .. is used between two values. The range of values is the whole set of numbers between and including the left and right operands.
Jbu rizbiwuly uhotyvu ghiucex u yuvsu mcuj 3 de 42:
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.