Stream/LazyList के Basics
एक LazyList अपने items सिर्फ तभी produce करता है जब मांगे जाएं, जैसे कोई कहानी जो अगला page तब लिखती है जब आप उस पर पहुंचते हैं। यह एक endless list को भी बिना एक साथ बनाए describe कर सकता है।
In this page:
Syntax
val lazyList = LazyList.from(start)
val firstItems = lazyList.take(n).toList
val infinite = LazyList.iterate(seed)(x => next_expression)
Stream/LazyList Basics
LazyList (Scala 2.13 से deprecated Stream का आधुनिक replacement) एक lazily-evaluated, संभावित रूप से infinite sequence है, जहां elements access होने पर ही compute होते हैं और फिर cache हो जाते हैं।
यह आपको एक infinite sequence define करने देता है, जैसे सभी natural numbers, और .take(n) से सुरक्षित रूप से सिर्फ पहले कुछ elements लेने देता है। #:: किसी LazyList के आगे lazily एक element जोड़ने के लिए उपयोग होता है, जो strict List के लिए :: जैसा है।
Warning:
किसी infinite LazyList पर पहले .take(n) call किए बिना सीधे .toList जैसा कुछ call करना कभी खत्म नहीं होगा।
उदाहरण: Stream/LazyList Basics
object Main extends App {
def naturalsFrom(n: Int): LazyList[Int] = n #:: naturalsFrom(n + 1)
val naturals = naturalsFrom(1)
println(naturals.take(5).toList)
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
आम गलतियां
- किसी infinite
LazyListपर.toListया.sizecall करना, जो कभी खत्म नहीं होता; पहलेtake(n)का उपयोग करें। - नए code में
Streamका उपयोग करना, जबकि यह Scala 2.13 मेंLazyListके पक्ष में deprecated है। - यह मान लेना कि सभी elements एक साथ compute होते हैं, जबकि
LazyListहर element सिर्फ ज़रूरत पड़ने पर compute करता है।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: