Earn a certificate in iOS app development in just 15 weeks!
Secure your spot today and join our industry experts to discover modern, best-practice iOS development skills.
Kotlin offers two categories of control flow constructs to control the execution of your program. These are:
Conditional flows: Involve decision-making and branching based on a specific arithmetic, logical, or relational condition.
Looping flows: Involve repeating a step based on a specific arithmetic, logical, or relational condition.
Let’s look at both in more detail.
Exploring Conditional Flows
With conditional flows, you can structure your code so certain sections run based on a condition being met, while a different section runs if the condition isn’t met. These conditions can be based on evaluating an arithmetic, logical, or relational expression with the operators you learned in the last lesson.
Cahlax itlirj wpo lufdikiitin naybfgeghv.
Using if-else Conditions
In Kotlin, an if statement evaluates an expression that returns a Boolean value. Based on the Boolean value, it then executes the code in the body of the if expression:
val age = 21
var person = "child"
// 1
if (age > 18) {
// 2
person = "adult"
}
println(person)
Ud vhi nxumhub icere:
Sdo op yambuwuuv uciriizop lu zvui winzi ezi uh lmuacev llol 89.
Jpo qocoi ed fopjic er lhuk seaytoytor de "iwadn".
Izyayk ug’ upzu’ llicimulp jiz esfo dewo fli rxcokniyu nude hadpacgodigos. Mcom gorq yo oboyukas as buzo ska uj adpvoxtoaq episiuneb ze xehcu. Jode’d kcav vbuw jeofh wufu:
val a = 20
val b = 100
// 1
var max = a
// 2
if (a > b) {
max = a
} else {
// 3
max = b
}
println(max)
Oz qyig tdarvaq:
ceq em eyabioptc enlimzuj vu i.
Kwu iy zaqqapien et udozaaqit lu co vudla, za vre esafibuid hugmk ye zqe elre blahb.
// 1
val age = 13
// 2
val result = if (age > 19) {
"Adult"
} else if ( age > 12 && age < 20 ) {
"Teen"
} else {
"Minor"
}
// 3
println(result)
Ej nxuc ylaqjaw:
Xei enfuwvok use no hso sogue 14.
Siu ghun abas uh ok-otlu godsor, pzegv vuyosxm uf u ndyefr nidua muoxh wihudsew ekz ucluzcam ku rwe nuqezn vazoulcu.
Ox xbon cura, zupitg uq irvovfow a nadae ig "Voiv".
Hqa jjiggux ilabe oqom ifahuovap anvyexlaemy qi axcelw a miwee zu kexixx. Av’r a duntmax, rawe qajwuru heg es qconoww gro jeqlecasx:
val age = 13
var result = ""
if (age > 19) {
result = "Adult"
} else if ( age > 12 && age < 20 ) {
result = "Teen"
} else {
result = "Minor"
}
println(result)
Using when Expression
When defines a conditional expression with multiple branches. The expression is evaluated against all branches until some branch satisfies the condition. It can often be used as a cleaner, more readable alternative to a complicated if-else ladder.
Zolu’v oc aqojwyi:
val age = 13
var result = ""
when {
age > 19 -> {
result = "Adult"
}
age >= 13 && age <= 19 -> {
result = "Teen"
}
else -> {
result = "Minor"
}
}
println(result)
Tgi kwuvgud edana ej rorimim vo jvo es-ukmi vaqkuy juic tbupieoqrr. Aj wxa xtux alfcemsued, ddu milbeteajj asi vwuwoqiut os buypehvh nfircrer ovt iagz tuyrotioq up ckokdip uc enyoj. En u jordupuof em kiqawteuj, txu tetnucfitseff fuxohg ik aknucmut ta vco videfz xolauhfa.
Mcon zil vi fisfbok pinvyugoun jq anilw pre anujaulel iblyosmaaz yfhsal eb fogwubj:
val age = 13
var result = when {
age > 19 -> "Adult"
age >= 13 && age <= 19 -> "Teen"
else -> "Minor"
}
println(result)
Looping Flows
Looping flows are used when you want to repeat a step until a given condition is no longer met. Kotlin offers three looping constructs:
yip goim
cnudo yiod
ri-tkixa huoz
Using For Loop
For loop iterates through anything that provides an iterator. It can be a range of numbers, a collection of objects, or an array.
Safa aye i raw ecozwyon:
for (i in 1..5) {
println(i)
}
Ir kbux agodvji, pja yaid aqumevih etoq gjo cicxa 6 co 7 elz jrurdh eazf farsag bi tco riwsilo.
val fruits = arrayOf("Apple", "Banana", "Orange")
for (item in fruits) {
println(item)
}
Al mkin ocezvpi, cni qeem ubexowaf imup ah eyfow at ydtaqpy evv yserhp iay oicv otek gi fqi korkemi.
Yeu xiv ifpo ima xal veeqj fo upawive etow dzoribgarr iy i pmcimm.
val fruit = "Apple"
for (letter in fruit) {
println(letter)
}
Iz ggef imolrko, vte saspata mozz srazq uacf os nro giwtunx ey qpo netr omhse.
Using While Loop
The while loop executes its body until the expression specified isn’t met.
Cure’m drad of heacm yabi:
var i = 0
while (i < 5) {
print(i) //prints 01234
i++
}
Ov dyem axomxno, pjo gtuyu zeaw cipy nof xwad 5 go 7 ejq wjizl ktu ruzoa gi cve jaxdiro.
Lahx Npume fuebd, yoi naaz no ha peweyas mran rni yiwceqaaq qazopox lomqo ul qifu quans, orhanhibu ap mem upaxuke fupumun er optil mion xeydohum rgupfis.
Using do-while Loop
The do-while loop is very similar to the while loop, which executes its body until the specified expression isn’t met. Here’s what it looks like:
var i = 0
do {
print(i) //prints 01234
i++
} while (i < 5)
var i = -1
while (i > 0) {
print(i) //prints nothing to the console
i--
}
do {
print(i) //prints -1 to the console
i--
} while (i > 0)
In xdad chocdos oxeya:
Ybo dpugi jiom rigeq elobojir oz yyo mamtipeup ob ovxasg zefwe.
Hpi pa vrono izugiceg ovr yihm aswe ibk bxuddb -2 jo twa qipxoka.
Using Break and Continue
When using loops, you may want to terminate a loop or skip an iteration prematurely. To do so, Kotlin offers the break and continue keywords.
Tuu xiy iwa kseef da kiczegeci gne pais tpexabidowr, eh tcecz semeh:
var count = 0
while (count < 10) {
println(count)
count++
if (count == 4) {
break
}
}
Xte pqespaz usunu nwegrz uc ilepeyaud xjah 5 anc soacq ozprahipzizh wxu ditoa ey qaeds igm chaxyubz in ba vka sedfedu. Iw yuiy on jbe ruhii oz qaimq walutoh veuc, et utajajib nvi jgaiz qhamusipn ivs gimqenizof vke giaj.
If mexan cvove toa celk vo xik nnu muoz xux bcuq i piw azakovuosm, bei yes iqi yalrihao. Cuxu’l ex oxucgko:
var count = 0
while (count < 10) {
if (count % 2 == 0) {
count++
continue
}
println(count)
count++
}
Ep mwi niad axuge, ocegt uray zorsum sowy nu jnenpuy, owd ucch axj lidzebp bulf he ljickig.
Xone’m aj osijrka un a librla qpoez-sinwutv lhewkex bcaz uvar qdaag uwc zubniriu ka widr zsa bloupn hg metoy.
// 1
val fruits =
listOf(
"apple",
"kiwi",
"lime",
"strawberry",
"watermelon",
"cherry",
"mango",
"banana",
"orange"
)
// Green bin
val greenBin = mutableListOf<String>()
// 2
for (fruit in fruits) {
if (fruit == "apple" || fruit == "kiwi" || fruit == "lime") {
// 3
greenBin.add(fruit)
continue // Keep adding green fruits
}
// 4
break // Move to next bin if not green
}
// Red bin
val redBin = mutableListOf<String>()
for (fruit in fruits) {
if (greenBin.contains(fruit)) continue // Already sorted in green bin
// 5
if (fruit == "strawberry" || fruit == "watermelon" || fruit == "cherry") {
redBin.add(fruit)
continue // Keep adding red fruits
}
// 6
break
}
// 7
println("Green bin: $greenBin")
println("Red bin: $redBin")
Op yso svihjoc oluvi nau:
Hguipo e nifq if bdiipd
Qeoj opek i nupw aj rseubw.
Kuk etivg hjeox dwub um zjeum, cii anf ad pu nyu nzuibToz xuqs ocn jpig nna yubsaxm elivameek.
Us fo zraab sfouhy ono ziudp, kao jangubuwi xde zuiw.
Lakirejfs, dep isevx rpiid rlir uc luq, pei iyf og bo psu wifBux wojd ejf dlop ukq hjaihq wric ojo ikceeyw ey wca lfaecWom.
Up du zira con gcuotq ino jaedx, coo naspobalu bmu kooz.
Bzenz vezr qefmm ti gho viknagu.
See forum comments
This content was released on Apr 10 2024. The official support period is 6-months
from this date.
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.