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

Future के Basics

एक Future एक ऐसे जवाब का वादा है जो बाद में आएगा, जैसे खाना order करना और एक buzzer पाना। इस बीच program बाकी काम करता रहता है।

In this page:

  1. Future Basics
Syntax
scala
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

val future = Future {
  // asynchronous computation
  result
}
future.map(x => expression)

Future Basics

एक Future[T] एक ऐसी value को represent करता है जो asynchronously उपलब्ध होगी, अपना computation एक implicit ExecutionContext द्वारा manage किए गए अलग thread पर चलाते हुए।

किसी Future के result का synchronously इंतज़ार करने (पूरा होने तक block करने) के लिए Await.result(future, timeout) चाहिए, जो आमतौर पर रोज़मर्रा के async code के बजाय simple scripts, tests, या program के आखिरी step के लिए रखा जाता है। इस तरह किसी Future को चलाने और block करने के लिए scala.concurrent.Await और एक ExecutionContext (आमतौर पर ExecutionContext.global) दोनों को import करना चाहिए।

Note: Await.result से block करना मुख्यतः scripts, tests, या किसी program के बिल्कुल आखिरी step के लिए उपयुक्त है -- production async code आमतौर पर इसके बजाय callbacks chain करता है।

उदाहरण: Future Basics

markup
import scala.concurrent.{Future, Await}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._

object Main extends App {
  val future: Future[Int] = Future {
    Thread.sleep(50)
    21 * 2
  }

  val result = Await.result(future, 5.seconds)
  println(s"Future result: $result")
}
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. ExecutionContext import भूल जाना, जिससे यह Cannot find an implicit ExecutionContext के साथ fail होता है।
  2. हर जगह Await.result call करना, जो thread को block करता है और Future के purpose को हरा देता है।
  3. Future के खत्म होने से पहले program को खत्म होने देना, जिससे इसका output कभी नहीं दिखता।
चैप्टर सारांश
  • Implicit parameters और type classes लचीला behavior प्रदान करते हैं।
  • Generics और variance बताते हैं कि types कैसे संबंधित हैं।
  • lazy val, LazyList, और Future देरी से computation और asynchronous काम को support करते हैं।
🔒

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.