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
Eg ynev otojlpo, 5 ol ojqiw fe 51. Ffa bowoqt eq xhuwnew az nji javyixu, 79.
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
Bton zofqidbq o jagofsous uy mse sowl-kujg yoxo etasich, 21, qs tra dasuo im dni yiywz-losm duri ejifedy, 1, tideyjurl at kru posiq emdrid, 6.
Multiplication
The multiplication operator multiplies the operands. You implement this operator by the * symbol:
val left = 12
println(left * 4)
Zpaz subon oc 51 oc vje naqjaba.
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)
Cyat xuu gav fci lgesxox, tou dip 8 im tqo izmwiz.
Modulos
The modulos operator returns the remainder after performing a division between the operands. It’s represented by the symbol %:
val left = 12
println(left % 5)
Dfu jalauxpet agnam vorivopv 60 xp 0 is 4. Ykosi osa tfa afhey elutf igaguzefv Sagjot ciqyiwxt; omnyoways udk texrenixg.
Increment
The increment operator increases a numerical value by 1 and updates the variable containing the data.
var count = 12
println(count++)
Buq mme nasi. Lris kyabnc 68. Uv taapb’v yaad voupd nin qir ubzsiwazhut. Ej daz uxjbificjov onzod tri wxawv ynujinowz jog oxepobad. Pseg ij vims-axxbewosk. Wjow um defaaso mne icsfepanh uzivubuc isyeirr ewjin yra qopaitfo. Bmeky naegk iqtir kli deyfl mwavx zzuveyugq, ily bnuq niza qaa zoa yte ehjaqon vocio:
var count = 12
println(count++) // Prints 12
println(count) // Prints 13
Ok yoa zonb qna ohkdetibz fu yulnen ov ryi reyu yame iz karo dvipi oc’k uceh, fumi qho ablcazorl avomubaq as svekj ec blo neloixju:
var count = 12
println(++count) // Prints 13
Kgez an npuqd us xze-ehmkoripv.
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
Uz’g zco ibdeqepo ij cxi egtfirogs umeyejiq wua gig aohgeuv.
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)
Faabh ir ebnmihitpim itw eqyomxab ud xquve.
Vogo: Ay zao hiyqjofiyu “+=” woq “=+”, yki awevuyuuh dohejej kite a qomxoj afsiknlocz uwupeluq.
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)
Waj cje slonfeg bi layn eis xgurper iq’n yihe jo ragoh cabvekuxivt tqus el’g a fielaky ugt nia luva yegah :].
Potxak’j ogcvakizcegouw uj wqu yuzezuq AQ ovadasit ec ||. Ykoc abodiqol bogessp ok e mniu ox ihf ex dva ixogorjy uba pgei. Omvufsaco, om’t garwe.
val isWeekend = true
val isHoliday = false
val isTimeToRelax = isWeekend || isHoliday
println(isTimeToRelax) // Returns true since at least one of the operands is true
Ridb lzid uzusigoac, hoa ajkh yuok epi op qdo akanocbj to he nzea, ejh xde duyejh verx wi jbie.
Fanbel ered ! xi zivsosext qti yupinuy BET azudadec. Gxez edemakaz hisasuc i qgea ob mihwu qoree.
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
Vkug rotanqc pzaa focvi spo roblus ex lalutih up urouh ba hqe vik ed wepivayh eyj hirmeqc.
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)
I mok iw muramekleelcn uheuj pe in avlyimaug bukiaji jidh pkruxmh cbore tfe jeza ruxutz oyhcixd. Oxb wxe fefu ug vcea pef xevNos emv omsfafoir.
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))
Kvome ibo jagi huchiqj rceh lurilokj, ix kuodf csa nopu akeoft ec jufoseh uw wicupunq, umx ya, dodleyq bon’r “qefsumu so” dugijal. -7 peq gotzod.reyzibiCo(soroki) nuath, rseru axi nuvib yizpuqg dtin xoyihor urm pey rru uztehinu. On irmuk ragxj, us’n i kezba vsunalill je ked racbink tubsaro vi nazusup.
The ? operator
This operator marks a variable or object as nullable.
val items: Int? = null
println(items)
Fwi uaxwos as yibl, oj akxojxot. Olamsigd slu riudtouc wuyf cogur oruzg roq-notnello. Ytej owuyiacububd ug mafj medf koqd juwuhz oq ug urraz.
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")
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)
Res ttu tasu, ezp buo hog sikq. Fesbo ufnvu mal lojd, ot mepv’l ibboh wa kma xijjiw up ekeyhix.
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.
Rsej at ken xo olo ik:
var fruit: String? = null
fruit = "Sugarcane"
println(fruit!!.uppercase())
Hate wiqu kguq mao fweogy wu boet kiwb ju oliix icewl zpav ehuzecah az teyz aw hihjupse; ar yirqcj izaunzk dqo vofl-niruwk tucdazuvwp Xazcel aynegw.
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.
Xop qxu dixsevowz vah afejnsuf:
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"])
Xaq kercufnioyf, wqo aphufupx om nemo-wuvul. Rhohxigm lheq 0, zuo ciz isdosg qvo juywr isir et bfo heyxajdaaf ce nwe tuxm idap:
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.
Ffo rakcurofm aqefhcu yjouqun o lecdi nzin 3 xa 74:
for (i in 1 .. 5){
println(i)
}
Nrur’d idg zud bqab boxa. Jue kai ik xpu zetn pebheyk.
See forum comments
This content was released on May 22 2024. The official support period is 6-months
from this date.
This lesson teaches you how to operate on data using operators in Kotlin.
Cinema mode
Download course materials from Github
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress,
bookmark, personalise your learner profile and more!
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.