← Back to Scala Course | Chapter 12: Advanced Features | Lesson 6 of 7

Stream/LazyList के Basics

एक LazyList अपने items सिर्फ तभी produce करता है जब मांगे जाएं, जैसे कोई कहानी जो अगला page तब लिखती है जब आप उस पर पहुंचते हैं। यह एक endless list को भी बिना एक साथ बनाए describe कर सकता है।

In this page:

  1. Stream/LazyList Basics
Syntax
scala
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

markup
object Main extends App {
  def naturalsFrom(n: Int): LazyList[Int] = n #:: naturalsFrom(n + 1)

  val naturals = naturalsFrom(1)
  println(naturals.take(5).toList)
}
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. #}
आम गलतियां
  1. किसी infinite LazyList पर .toList या .size call करना, जो कभी खत्म नहीं होता; पहले take(n) का उपयोग करें।
  2. नए code में Stream का उपयोग करना, जबकि यह Scala 2.13 में LazyList के पक्ष में deprecated है।
  3. यह मान लेना कि सभी elements एक साथ compute होते हैं, जबकि LazyList हर element सिर्फ ज़रूरत पड़ने पर compute करता है।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.