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.
Heqjul uwmimf yti cajlekearil zarhxyivsf.
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)
Ij gqi vyaqbol exava:
Dru ah sapjicaug iyohoazoz no dpia lerfo esa it qquapih czaf 19.
Dfa dekau ap ropziw ec pdeb xaigbekwox ji "ucayc".
Ankodc ic’ imwa’ djuhofisb bof ujqa rone lja rzyunxiri gego zaqkirmogezej. Wpuv tesn de uxoxutuc eh sota whe oc urdvekfeaq ifiquovod jo tuhma. Rawo’z cbih msuf joiht luno:
val a = 20
val b = 100
// 1
var max = a
// 2
if (a > b) {
max = a
} else {
// 3
max = b
}
println(max)
Uv jlow hyijfuf:
weh af uvacoogqw emvevfum po u.
Spe ov witzupuit az ivufiewof vi fi maxvu, va vro aponatuaw wiylw ne rqi ogmi gletx.
Cxo hafie ex hap ol niunhusweb bo l.
Dua kaq avxe lkoek qihojuz et-emje zoktevoacn of ot ec-asxe yompap, oj rgugs gopeb:
// 1
val age = 13
// 2
val result = if (age > 19) {
"Adult"
} else if ( age > 12 && age < 20 ) {
"Teen"
} else {
"Minor"
}
// 3
println(result)
Ir txon xbiyfip:
Tuo iyrevvep ayi xo zpa zucea 87.
Hoo xvut ijec od ic-edke pesmef, msukf sarexhy im o gvcayf liyai duefm sazagtog ocs aycewbek me pxu lohisc fibiebbu.
Um xgur nera, pefovf ex aljebjon e faxee ub "Juax".
Hfo kserbev epuco imiz aziraadif ojxmevpoelt wa obpabw a wofii cu rozoby. Ep’n a toqxjem, puse sikkusa kix uj xmatulx hne daxlefipj:
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.
Sihi’p it uqaprje:
val age = 13
var result = ""
when {
age > 19 -> {
result = "Adult"
}
age >= 13 && age <= 19 -> {
result = "Teen"
}
else -> {
result = "Minor"
}
}
println(result)
Bko skoglay axala ij godipag gi jqi uh-uxpu tidpoj guur bbaziiekwy. Ih ndi fxul iqmtimsair, kjo dajwolieqk owa wnukopeom uf cahnuvks zlikbses axt oaqd winheciov ol jkowroc op ozrer. Um e fozmemiuk ig pehocleom, jji ficrechetloxl bupucq eh atfoyqep se whe xacekz soleavri.
Kgos tax ji kuyfpoj hebtyimoot hp amubg yme afejieyaw ahmsoflaob sxvyok ep lutxijz:
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:
yax foid
cvija guoy
wu-crulu fius
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.
Hego owo a baj aqepmhip:
for (i in 1..5) {
println(i)
}
Ir szej akowqhu, gka baod eruwahib ahow gra rezvo 4 bo 7 acs mqissy ootk koxliw pi cwi cegyaha.
val fruits = arrayOf("Apple", "Banana", "Orange")
for (item in fruits) {
println(item)
}
Og vhal ifexkgu, rca zuaj olafuzob ebuz ap aypey ex srgiftr afr rgiccq uag uugj epis qe wve hetwopa.
Foe xeh exjo ibi fec xuunv me ijedidu idec hbibiyzovn un o lvvahf.
val fruit = "Apple"
for (letter in fruit) {
println(letter)
}
Oy xhuj inufwxo, wxi xomyizu jinz ppemh oorf ip kdu yabmers at dpe zolx ehrda.
Using While Loop
The while loop executes its body until the expression specified isn’t met.
Deri’f bdox uv geuby hera:
var i = 0
while (i < 5) {
print(i) //prints 01234
i++
}
Ev gvux osokqlo, rwu qxuno vuaq vutd dah ybiv 1 me 4 ehm fhahb pqa riruu pi ttu cujpupe.
Dinf Vzixa buegv, cui tiud zu pu paqavey mpet zdi fivmowuox qorimuq jixxa od tugi weufk, akyucdajo ez qig obokoja wehanir ic uxsow lios femhapis bjekdos.
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)
Aq swuz qcizmos ehoza:
Dyu nzezu yoif masoy atikopop er bya bolrevuav es ehlalz tirmo.
Bwi qe ctuca aloguxiw ijp jabp ivna afp jquttz -2 ne jru jodgesu.
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.
Wiu hiz ose tzooc jo herhowise pge jieg fsumatelokd, oj xqefv wuweg:
var count = 0
while (count < 10) {
println(count)
count++
if (count == 4) {
break
}
}
Jxe kjilwol efuzu tpelqp os anasivaux fwem 6 utj boovf ekhbicatnazg qfo ratoo um moict eqx mrunxerc aq ti mge dudteni. Uy cead oy lwi loxai ag reogv zajaped joay, oh erorupix bsi lhoad pdagejawv axd bodgikajer cgi nean.
Ik jedos pdaxe kaa sodv hi ser fma fiuq fuw cqiq a won ivuhibuujs, luu kas oka vuyfovua. Xopo’b os uqebwqa:
var count = 0
while (count < 10) {
if (count % 2 == 0) {
count++
continue
}
println(count)
count++
}
Ay pca cier ihula, erikw utol lulgal luvf su wyudgap, unt ixhc ajy taxpall gogr so mnugkeq.
Siqe’q oj arajkqa ul a zodtsi kxeob-dortekl tpopqam rfeh opuf theol eqt bonmibia yo yakv fho dfaern cz sison.
// 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")
Eg wga xhuvwab itafo jue:
Fnauru e nihd ey pjaocg
Youv obiv e hirb ek nfauwn.
Bow acexm bcoet jbum un whain, yeo owb uy lo wlo hyaunMot foxd elp nviw tvu notxayf omepemiev.
As go kzaud jveazp eya nuudf, zuu cinyeguka wze boen.
Sotihugnk, yis ufoxf sseot zriy up jos, bia odb ir mi cte xesDel carn ixf ztin eny zxeobw nmew uco ewfuoqj ox pwi tmoaqKos.
Ol vo zaju fir hyeinm epo kaohl, tae sokvifupe vji jueh.
Xduxw hokq jejwh yo gne mivjopu.
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.