Open In App

Futures and Promises in Scala

Last Updated : 01 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

1. Explanation of Futures and Promises in Scala:

Futures:

In Scala, asynchronous computations are represented using futures. They are used to manage lengthy calculations, including requesting information over a network or retrieving data from a database. The outcome of an asynchronous computation is included in the future, which could already have been calculated or might be accessible at a later time. Using combinators like map, flatMap, and onComplete, you may build asynchronous actions and mix them using futures.

Promises:

Futures and Promises have a strong relationship. They provide a means of adding value to a future. In essence, you are establishing a Future whose value you choose when you make a Promise. Using the success way, you may finish the Promise with a value; using the failure method, you can finish it with an exception. Other software components may access the calculated value or handle the exception when a Promise is finished since the associated Future is updated with the outcome.

2. Code Example:

Scala
import scala.concurrent.{Future, Promise}
import scala.concurrent.ExecutionContext.Implicits.global

object FuturePromiseExample {
  def main(args: Array[String]): Unit = {
    // Creating a Promise
    val promise = Promise[Int]()
    
    // Creating a Future
    val future: Future[Int] = promise.future
    
    // Completing the Promise
    promise.success(42)
    
    // Handling the completed Future
    future.foreach(result => println(s"Future result: $result"))
  }
}

Output


Screenshot-(363)


Article Tags :

Similar Reads