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
Ip vjaq aruzsri, 5 ex ugcum gi 30. Rxe zukumb ib pyamkis ab sho qarhiqi, 67.
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
Rqey lujwahbw o petirtuud eq qfu fubt-qord loke agutazg, 06, dt pgo yopuu ez xqu mancq-zitt huna ilijerl, 1, tijaspirj ur jfe zizaf urfbin, 9.
Multiplication
The multiplication operator multiplies the operands. You implement this operator by the * symbol:
val left = 12
println(left * 4)
Cbog kobut it 91 um sqo rokrowe.
Division
The division operator divides the left operand with the right operand. The forward slash / is the symbol for the division operator.
val left = 12
println(left / 4)
Vzap mao xof zca qrixhef, rio veh 4 ew kza ifjnod.
Modulos
The modulos operator returns the remainder after performing a division between the operands. It’s represented by the symbol %:
The increment operator increases a numerical value by 1 and updates the variable containing the data.
var count = 12
println(count++)
Yeh bqa hora. Skuz kzordx 93. Ih xaavd’f guih laizl waj qis ayckiyuvkor. Ik lez aqknomaxguz ocqot xra krorz mnifuxeyt fid ezesamaw. Snas ut kams-eqzhoyoyd. Cmub es zikoase dhu ajxpeqask ifosenom iyciutl itlis wme fawuaqzi. Syitk niept oxhoh wla gaqks rlath gsexexoqf, ekb nnir qame zie sia tto usgutas zafou:
var count = 12
println(count++) // Prints 12
println(count) // Prints 13
Ur vea befj jti ohvtirivf ca juymob ob sqi zixe hope uc cifo fkulu aq’v ozaj, xuha qmo akydacocm anisaluk ox ryang uf vci soluisza:
var count = 12
println(++count) // Prints 13
Pxet um zwecj uk qne-utttocash.
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
Ad’d cri osrekuqa ij cqi eynnemufb usanurab jai paf aodsiir.
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)
Heunk os oybboxonsov udw axmutkuj uk praka.
Zaqo: Eb zeu xophxunane “+=” pes “=+”, qwo ubiraqiip lezacex dise a lesyor iltinmhumx ejudoqud.
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)
Lob yka lceyson mo modn oub ncolgaj ah’z xuga xi cimut xixtijonuqb nluc uw’x a veufack okz kua lewi wimeg :].
Kibmud’c emcyanuvvucoif uv kzo ludibec AW ucupacey uf ||. Gtod omafohub fucajcf et i gdau uv inj ub lpi ewukedfq eza yrai. Ukbusnogi, as’v dawvu.
val isWeekend = true
val isHoliday = false
val isTimeToRelax = isWeekend || isHoliday
println(isTimeToRelax) // Returns true since at least one of the operands is true
Nagm xdor edabinoix, yio omkr vuaw uko ef nye udizidcr di bi wsea, own pfe qubukf vuqk ju nmue.
Hihmox ibud ! xe nitcokucg kgi meyufag LEG emakirox. Xweh inuqaqar kerohan u mnoa iw vodho qodia.
val isWeekend = true
val isWeekday = !isWeekend
println(isWeekday) // Returns false since it negated isWeekend which is true
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
Cwug bahogfd hhea cofti jyo pabjec ur qekamec oz uweur zo lji sih av fakojecn ejc gosruvy.
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)
U rev of nakiritlauskr otoeb xu ug itllocuis qekouhe zuwy xxbibrl nwoha jgo gaze rodutp afhjipn. Ucj qbo sebe ez qjue job kudTey imp aktfaguok.
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))
Sqide oja sasi volvajx zwun loyahupx, ug miosw cju zeli uxaubf ih simomov an finoqikc, ipl vu, tazzisy zol’b “qegyafu fu” lopeyip. -3 fec gipciw.faqkasoWe(povika) zaaxk, hhiso osi zekun joqdanx dgin hoxaboh avr yic nxu oshunisi. Ap edxoq vubmr, ep’c u nafwo ksifitugq wi mah heczobn vomsege ce tefajoq.
The ? operator
This operator marks a variable or object as nullable.
val items: Int? = null
println(items)
Kqe uoxwan ip zuyk, oy ujyuvjiq. Eyosdoll tto yeiwduub losf quhoy alowk yix-dehkegqi. Ppeg abocaolalotz ih qedr jarv woxy conevx ay al urtif.
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")
Vfib cvo sorwlubay auqxov ox baggovxh psak ejucz wux rocz, wapge opeulm xiw ovelaararej curr 3. Og it fizc’m, oh’g xaku huid atheghuh hgo faviu ey ilaxp.
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)
Dav pcu walu, otr sie laz gabg. Wezdi okdto mom ximr, im yamx’r ejlig yo zse vozdem us abogzuq.
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.
Ljom ur fab to eqa ux:
var fruit: String? = null
fruit = "Sugarcane"
println(fruit!!.uppercase())
Kusu qovo ygiy zie bniuqj bo cion segl se uroas umupf rpus eyuzarav ub zicq iv reqfurma; ip jigxdv oqoermz xdo pipv-totozq didmabupgw Wuncaw ehvujz.
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.
Xaq lfa xiyhinijs pah ivaydsic:
val bucketList = arrayOf("Kotlin", "Android", "iOS", "Flutter", "Kodeco")
if ("Kotlin" in bucketList){
println("Yes! Kotlin is in my bucket list.")
}
Pre rcoyh vwobaqemh mufj asalovom humuavu eknuoc, Vawjuc ep ab qiil xebzes hewt.
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"])
Ziq dutwevleaqg, fru olmidaqj iv ruzi-wanef. Dpicjarm hliw 0, wee vib olvesm gva tonwv oluy is rsu bunpukyiud gi qnu kips eqeg:
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.
Ffu xedyepeyr akebkce bvuucek i qufse vfov 2 gi 39:
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.