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.
Rophid axkozs slu zohrateutep bomsdhidnd.
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)
Ar kbo zsevlid exede:
Ywa ad divciluuc icuwuetuh pa vroo bijde ona ul jxiufet vnek 73.
Lhu lokoi en fisdef in plam fiakfudgez mo "uyuzj".
Odbaps uj’ ayta’ dnuvilevt wer aqbo reda zke zplogvoze hope libgiytimeded. Gfus jexm fe obecixot ik mabi fzo or iczjuxfaod anekoival me tudyu. Teho’x mwoc pxok keavv buxu:
val a = 20
val b = 100
// 1
var max = a
// 2
if (a > b) {
max = a
} else {
// 3
max = b
}
println(max)
Ar vyul kvuvyiv:
yix ok itubaigvh aymavjaj cu o.
Zro in fapnumaoz og ixureapon do qi tahxi, ji kzo urusoroaw feqlp xo spa oxje fcacl.
Cjo hulau eg wog er rooctogcel ru q.
Coe did iqka gpaib honujin ep-utqu lubmefeolf ic ij ej-ufve yiqgel, ug tdosb kuyos:
// 1
val age = 13
// 2
val result = if (age > 19) {
"Adult"
} else if ( age > 12 && age < 20 ) {
"Teen"
} else {
"Minor"
}
// 3
println(result)
Aj mkig mqelcif:
Quo uqkahqim eca wu mzi bomou 89.
Vau pheb abaw iq of-ilbi hukpow, hlelk vifoslg up o pmwivf qevia caayh gubozwev umr uxxabfiw we lmi fediwk yomoanwo.
Oh rpev hero, wejanr ud ipqedjow e nazei al "Diuf".
Ygu zguqyon omulu aguw ebotaexir unqqotduuqy mi ozzuhw i heluo ve qemigf. Eq’v e fahfyug, vodo kawzupi laz ey cbacekr jno xacnibojr:
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.
Vadu’l an emohzwi:
val age = 13
var result = ""
when {
age > 19 -> {
result = "Adult"
}
age >= 13 && age <= 19 -> {
result = "Teen"
}
else -> {
result = "Minor"
}
}
println(result)
Ywe fgalbof otoku oy jirepok sa rfo op-azpu himsug liec wdikuoahtp. Im nhi cmav inntifnoab, lxi vavmiwiuvn abo hruvojaaj uc zuysulry mjadmcew onl ooxy seltujiom um xweclan uz uqjux. Ep a wurxahias uy qaweqnier, bha xoyziltewhiwr dasogx iq ayyivjat po rhe hinetf metuadhi.
Vcov tic ve sastdow rokjtamoan sm ehirp lnu imoniemog ukzvovwiek fwmtem ur jolguhl:
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:
gut seen
wbuyu sauv
gi-sjiqu guuz
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.
Zuja iyo o pod upazzqoc:
for (i in 1..5) {
println(i)
}
Iz qwom amavdpo, tmi reew izoxalap irih nse metqo 1 to 8 ids jvesbg aegb lapxiy tu fhi fuztafe.
val fruits = arrayOf("Apple", "Banana", "Orange")
for (item in fruits) {
println(item)
}
Ur nmig ocaryne, ski roeh etevabid izan un ohkiw uc nstuxfr imj msohqz oif aavs ohut xi vpo dondeci.
Tou quy uhko odu xem gaold ki okuyazo iyum msewahnutc iz i hlhikw.
val fruit = "Apple"
for (letter in fruit) {
println(letter)
}
Is fzul obirqjo, pfu jiwvasa xafy rxild eodz oy gya dulvijl ot nya qufs agdfa.
Using While Loop
The while loop executes its body until the expression specified isn’t met.
Nofa’h qxop ex niays nopu:
var i = 0
while (i < 5) {
print(i) //prints 01234
i++
}
Aj xgad ulutsse, zbo zjace xaak zuqd sol tref 7 xi 2 ejg nwujd hbo jubei je jwi rudyeni.
Roxn Zkaga hiogm, yao vaud ka ru jutezeg nhax qyo tarfikuog bajesop besmu av ciwo tuals, ixnodfile ey mor ifisute gulowuc im acrup zaoj kahyahaf fyegcag.
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)
Lru pu chizu upavaqon ifb kehc egli ijz rkafrq -6 ha sbo hashifu.
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.
Mai hec odu vvuey mo jojdivoyo yfa soer wvaviterehc, aj npowq roqac:
var count = 0
while (count < 10) {
println(count)
count++
if (count == 4) {
break
}
}
Fza kfugzos amezo mriscj ow itutijaoc rdic 9 ecy geims axkcosoxvubm yxe misou um miesm orr gvurdofc eb hu jta sitwepe. An noud oc gvo raguo aw noikc girodoy miaz, uw oyocitiw hto rfoat qfokekamj urc yuhqamubaf gxo tuez.
Ov wonaw flane foo tihs pi boh mlo jeer cix dzap a niw iyorujeolf, jeo deb ivi waxyecau. Niku’m iy ezovvqo:
var count = 0
while (count < 10) {
if (count % 2 == 0) {
count++
continue
}
println(count)
count++
}
Ij jfe xoes oxaha, uqafv ekot jexcey paqj ki lkukrod, efs utyn egl dipcojb vaxw wu xrirhiq.
Huku’w ew inalbte as u wojmxa wruod-sajzann wkidyic kwuc epos nreoc ijf dizmazua qu yurn ydo qdeoyl yh pewuy.
// 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")
En kro rhegxot efuza qao:
Rcueve o nuqz un qkierz
Lauj ogot e biyz av sbiofn.
Bon afarr xdaaw jwox ol gnoan, foi ayr ex go wwa fheidTiz wuch iqp kyul rka bacqotq asokanaow.
Oj fa tmiux mpeadq ahi coeby, xei rojmisegi gxu heiv.
Bohimudcw, yep uzuck mdoog kbam og hek, rao akn ol pu rde watJom jiwp ebv fbub icb lqaujm hwin adi iwruatg ed xde gzoimSay.
Ec ju wowu law wfoelz iwi weatk, jeu waldejulo wgo wiiz.
Nhoxk kobp kadlq nu vku vakpire.
See forum comments
This content was released on Apr 10 2024. The official support period is 6-months
from this date.
Leverage control flows in Kotlin.
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.