Scala Concurrency and Futures 1 — Questions and Answers
Question 1: What is a Scala `Future`?
- A delayed computation that may complete asynchronously with a value or failure (Correct answer)
- A value that will never change
- A scheduled task running on a timer
- A lazy val with error handling
Correct answer: A delayed computation that may complete asynchronously with a value or failure
A `Future[T]` represents an asynchronous computation that will eventually produce a value of type `T` or fail with an exception.
Question 2: What implicit value must be in scope to create a Scala Future?
- implicit val context: Context
- implicit val ec: ExecutionContext (Correct answer)
- implicit val dispatcher: Dispatcher
- implicit val scheduler: Scheduler
Correct answer: implicit val ec: ExecutionContext
An `ExecutionContext` determines the thread pool on which the Future runs; it must be available implicitly when creating Futures.
Question 3: How do you handle the result of a Future with a callback in Scala?
- future.thenApply(f)
- future.onComplete { case Success(v) => ...; case Failure(e) => ... } (Correct answer)
- future.subscribe(f)
- future.listen(f)
Correct answer: future.onComplete { case Success(v) => ...; case Failure(e) => ... }
`onComplete` registers a callback that receives a `Try[T]` (either `Success` or `Failure`) when the Future completes.
Question 4: What does `Future.sequence` do in Scala?
- Sequences Futures to run one after another
- Converts a List[Future[A]] into a Future[List[A]] (Correct answer)
- Cancels all futures in a list
- Finds the first completed Future
Correct answer: Converts a List[Future[A]] into a Future[List[A]]
`Future.sequence` takes a collection of Futures and returns a single Future that completes with a collection of all results.
Question 5: What is `Promise` in Scala concurrency?
- A Future that always succeeds
- A writable, single-assignment container that you can complete to fulfill a Future (Correct answer)
- A concurrent queue
- An alternative to Future for blocking code
Correct answer: A writable, single-assignment container that you can complete to fulfill a Future
A `Promise[T]` is a writable container that produces a `Future[T]`; you complete it with `success(value)` or `failure(exception)`.
Question 6: How do you transform the successful result of a Scala Future?
- future.then(f)
- future.transform(f)
- future.map(f) (Correct answer)
- future.apply(f)
Correct answer: future.map(f)
`future.map(f)` returns a new Future whose value is obtained by applying function `f` to the original Future's successful result.
What is a Scala `Future`?