Using Labeled break and continue in Kotlin
📖 Scenario: Imagine you are organizing a small sports event. You have a list of teams and their players. You want to find the first team that has a player named "Alex" and stop searching once you find it. Also, you want to skip any team that has no players.
🎯 Goal: You will write a Kotlin program that uses labeled break and continue statements to efficiently search through teams and players.
📋 What You'll Learn
Create a map called
teams with exactly these entries: "Tigers" with players ["John", "Alex", "Sam"], "Lions" with players [], and "Bears" with players ["Mike", "Anna"].Create a Boolean variable called
foundAlex and set it to false.Use a labeled
for loop named teamLoop to iterate over teams. Inside, skip teams with no players using a labeled continue. If a player named "Alex" is found, set foundAlex to true and use a labeled break to exit the outer loop.Print
"Found Alex in team: <teamName>" if foundAlex is true, otherwise print "Alex not found in any team".💡 Why This Matters
🌍 Real World
Using labeled break and continue helps when searching through complex data like teams and players, allowing you to stop or skip parts efficiently.
💼 Career
Understanding labeled loops is useful in software development when working with nested data structures or complex loops, improving code clarity and performance.
Progress0 / 4 steps