break और continue (scala.util.control.Breaks)
In this page:
import scala.util.control.Breaks._
breakable {
for (item <- collection) {
if (condition) break
// body
}
}
break and continue (scala.util.control.Breaks)
Scala में कोई built-in break या continue keywords नहीं हैं, क्योंकि जल्दी loop exits इसकी functional style के खिलाफ जाते हैं, लेकिन scala.util.control.Breaks एक break() function प्रदान करता है जिसे breakable { ... } block के अंदर जल्दी exit के लिए उपयोग किया जा सकता है।
Scala में continue का कोई सीधा equivalent बिल्कुल नहीं है -- idiomatic code किसी iteration को skip करने की कोशिश करने के बजाय loop body को if guard से restructure करता है। Breaks को एक escape hatch माना जाता है, रोज़मर्रा का idiomatic Scala नहीं।
उदाहरण: break and continue (scala.util.control.Breaks)
import scala.util.control.Breaks._
object Main extends App {
breakable {
for (i <- 1 to 10) {
if (i > 5) break()
println(s"Value: $i")
}
}
// No continue keyword -- use an if-guard to skip instead
for (i <- 1 to 6) {
if (i % 2 != 0) {
println(s"Odd: $i")
}
}
}
Login to try C/C++/Java/PHP code in the editor
- loop को
breakable { ... }में wrap किए बिनाbreakका उपयोग करना, जो exit करने के बजाय एक exception फेंकता है। continuekeyword ढूंढना, जो मौजूद नहीं है;breakableblock किसी iteration को skip करने के लिए loop body के अंदर जाता है।import scala.util.control.Breaks._भूल जाना, जिससेbreak()औरbreakableनहीं मिलते।
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: