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

Lazy val क्या है

एक lazy val तब तक गिनती होने का इंतज़ार करता है जब तक आपको पहली बार इसकी ज़रूरत न हो, जैसे dinner सिर्फ तभी पकाना जब किसी को भूख लगे। उसके बाद, यह जवाब याद रखता है और काम नहीं दोहराता।

In this page:

  1. Lazy val
Syntax
scala
lazy val name: Type = expensive_expression    // evaluated on first access only

Lazy val

एक lazy val अपने initializer के evaluation को तब तक टाल देता है जब तक value पहली बार access न हो, declare होते ही नहीं, और computed result को बाद के सभी accesses के लिए cache कर लिया जाता है।

यह महंगे computations के लिए उपयोगी है जिनकी हमेशा ज़रूरत न हो, या values के बीच initialization-order समस्याओं को तोड़ने के लिए। एक साधारण val के विपरीत, किसी lazy val को पहली बार access करने पर इसकी initialized state जांचने और सेट करने का थोड़ा overhead होता है।

Note: एक lazy val का initializer बिल्कुल एक बार चलता है, पहली बार access होने पर -- बाद का हर access सिर्फ cached result return करता है।

उदाहरण: Lazy val

markup
object Main extends App {
  lazy val expensive: Int = {
    println("Computing expensive value...")
    42
  }

  println("Before accessing expensive")
  println(expensive)
  println(expensive) // no recomputation, uses cached value
}
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. यह उम्मीद करना कि एक lazy val definition पर चलेगा, जबकि इसका code सिर्फ पहले access पर चलता है।
  2. ऐसा lazy val उपयोग करना जिसके initializer में side effects हों और यह हैरान होना कि वे कब होते हैं।
  3. किसी hot path में lazy val का उपयोग करना और thread-safe initialization की लागत भूल जाना।
🔒

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.