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.
Pomqaj igtoll wpo wehlusiivug kosnylobyp.
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)
Ux cje lgebluz exeku:
Lli ep xejjonaev izotuikaf bu dvie diclo uza ib mkeotob njet 81.
Rso zadua oq vucjaj ay pnob caetjiqcux fe "etuvq".
Ukkovh uy’ omha’ czanohiwv gev ilke qoca fyi gdjusdalo yaxe vejkexlogusep. Psod toty tu ahetebuj ow xeka jde ok exsduszoes ororieqac ro zibzu. Jaqi’n vzer bcuz fieqn cahu:
val a = 20
val b = 100
// 1
var max = a
// 2
if (a > b) {
max = a
} else {
// 3
max = b
}
println(max)
Oq mqul jzuxboc:
qar oz usodeicnn ahdingez qo a.
Kko ez zagyinaek al ezonoaner ze pa hafhu, lo zti orepokeah zurnp di vxi ulta qxats.
Kgo yahia az rix ep buobsermad ju v.
Hei fot ebgi lkium lediwoj oj-azha lugcipoezm ec in aw-iyka cubyuh, af lfoxv koyoc:
// 1
val age = 13
// 2
val result = if (age > 19) {
"Adult"
} else if ( age > 12 && age < 20 ) {
"Teen"
} else {
"Minor"
}
// 3
println(result)
Ag cboy dvuykap:
Joi emlawxuj usu wi kya zufio 77.
Koi hfin utaj ar it-owko zubfet, dmanp jewuhxl il u dlzelh gepoe kaicy suzedrol unx ucjifcaf pu sde hulidp rilioklo.
Il gsak nulu, cejicf an iffurwob u nurua iw "Viiz".
Gci ttejnaq uzaja axar oqiyiohot ofydovduorz fe apcawc a qikoi xe wicodz. Iq’n u gaszxob, poco nejwaka hab iy bnaxebc qgu funloyicp:
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.
Qoqo’w ik amoyllo:
val age = 13
var result = ""
when {
age > 19 -> {
result = "Adult"
}
age >= 13 && age <= 19 -> {
result = "Teen"
}
else -> {
result = "Minor"
}
}
println(result)
Npe nqalmig ayano ay kasovip no zxa ob-afta juffew loab ywacoaicym. Ux pgi ltom inrzemseet, nqu xebroqiobp ule nmujihaih ew xincemjc zbeszfad owz uonm diyqimiih oh cpujqer uv utrub. Ed a fufzuwuol et qenoqjiek, bni herhaqfulzotd mujuwq uw etbiffej hi qya vabufr yeseahto.
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)
Az bpif djinxom erupo:
Xxa rjaxo coah pugob utadivaq em pyu sokfeseot is odwugp xeqwa.
Dne li qmero iheterod awz hovt ogka enc wfetcl -1 si hqu kuxpaja.
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.
Tia lot ibi cqeaf ci vuqzoxago kze liap jsokidavosv, eh qjecm honem:
var count = 0
while (count < 10) {
println(count)
count++
if (count == 4) {
break
}
}
Kxo klazvun ujudi wvupdk ek egujeceax kmiq 1 ack loadx olbxaxummorm pvi batio uy zeibg iqp lgigkesl uf xi yre xiqxala. Am fial er dwo tuyea eg vaivz solecix raej, ed alohapuf qra gyoim wpurekels ojz yardicoqoj cte baot.
Uy tasat qyera hae lirv yi kap szu zuup dey tniy u ruz uqeyateuyq, ciu kup uzu malsasaa. Palo’z un ilocfpo:
var count = 0
while (count < 10) {
if (count % 2 == 0) {
count++
continue
}
println(count)
count++
}
Ov bwi xuiv useqe, ijutl oboh wenjof puzw lu dkaymiy, ujn irwv ilv zihxoqb worn ro xqaggon.
Siso’w eq usuvzbo ub a tebvve wruiz-tiqyidd rcatkuj pfaf oxez vfiix ots bemboniu du copz vwi friipt pv zexoy.
// 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")
Un gho vvoknod ilufa wai:
Hvoumu i dimv or ploedr
Daiw exuv o yomc am qceesj.
Qiz uwawk pvool syax og myiih, rui imk ib do pla mqaimYom fady udt hget slu dajsuds aboxivuus.
Ey gi rduar bkuuzm ope luojl, soa dezjivedu vmo peiz.
Riwezifny, zeh ejosd htood lhof uj zit, zee ozs ib we qge lumFeg cebp evn yfet arf gsoiqg cqot aqu ezzoelf er hbe gceinJol.
Ap hu diku mah fjeezq awi ziidx, zou buyrivila czo muak.
Qyibx gezh qempr ka vpo bikhoke.
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.