Open In App

How to convert future string to string in Scala?

Last Updated : 25 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will convert future string to string in Scala. We use three different methods to convert future string to string in Scala.

What is the future string in Scala?

“Future” is a construct for asynchronous programming in Scala. It is an indication of a computation that, albeit not finished yet, will eventually provide a result. With the help of futures, you can run code asynchronously, allowing the programme to complete other tasks while it waits for the computation to finish.

Methods to convert future string to string in Scala:

  • Using Await.result
  • Using onComplete callback
  • Using map or flatMap

Let’s apply all the above three methods to convert a future string to a string.

Method 1: Using Await.result

This technique is simple and useful when you need to halt the current thread until a future completes and returns its outcome. It is important to use it with caution, particularly in production code, as it may result in performance problems, particularly in systems with many concurrent processes if the thread is blocked.

  • Await.result is a blocking operation that waits for the completion of the Future.
  • It requires two inputs: a duration that indicates how long to wait, and the Future to wait for.
  • Await.result returns the result if the Future finishes in the allotted time.
  • Await.result raises an exception if the Future fails or takes longer than expected to finish.

Syntax :

Val result_variable : String = Await.result(futureString, time_in_seconds)

Example :

Let’s look into an example using Await.result :

Scala
import scala.concurrent.{Future, Await};
import scala.concurrent.duration._;
import scala.concurrent.ExecutionContext.Implicits.global;
object Main {
   def main(args: Array[String]) {
     val futureString: Future[String] = Future {
       Thread.sleep(100);
       "Hello, Welcome to Geeks for Geeks  !!!";
     };
     val res: String = Await.result(futureString, 5.seconds);
     println(res);
   };
};

Output
Hello, Welcome to Geeks for Geeks  !!!

Method 2 : Using onComplete callback

onComplete callback method lets you to register a callback that will be triggered upon the success or failure of the Future’s completion. It is a non-blocking method that works well in situations where you wish to take an asynchronous action after the Future has finished.

  • onComplete is a method of the Future class that takes a partial function as its argument.
  • There are two cases for the partial function: Success and Failure.
  • The Success case is triggered and the result is provided to the function if the Future executes successfully.
  • The Failure case is triggered and the exception is delivered to the method if the Future fails.

Syntax:

fututreString.onComplete{ }

Example :

Let’s look into an example using onComplete callback :

Scala
import scala.concurrent.{Future, ExecutionContext};
import scala.util.{Success, Failure};
object Main {
   def main(args: Array[String]) {
     implicit val exc: ExecutionContext = ExecutionContext.global;
     val futureString: Future[String] = Future {
       Thread.sleep(1);
       "Hello, Welcome to Geeks for Geeks !!!";
     };
     futureString.onComplete {
       case Success(str) =>
       println(str);
       case Failure(exception) =>
       println(s"Future failed: $exception");
     };
     Thread.sleep(20)
   };
};

Output
Hello, Welcome to Geeks for Geeks !!!

Method 3 : Using map or flatMap

map or flatMap methods are used to change the value of a Future’s result or apply additional calculations to it. They combine well with other asynchronous processes and are functional. Whereas flatMap is used to carry out additional calculations that yield a Future, map is used to modify the result without altering the type of the Future.

  • map: It takes a function that transforms the result of the Future. The function is applied only if the Future completes successfully.
  • flatMap requires a function that yields another Future in return. It comes in handy when you need to chain together several asynchronous activities or execute asynchronous operations one after the other.
  • It’s essential to handle errors properly when using map or flatMap, as failures propagate through the chain of Futures.

Syntax :

futureString.map{ }

futureString.flatMap{ }

Example :

Let’s look into an example using map or flatMap

Scala
import scala.concurrent.{Future, ExecutionContext};
import scala.util.{Success, Failure};
object MAIN {
   def main(args: Array[String]) {
     implicit val exc: ExecutionContext = ExecutionContext.global;
     val futureString: Future[String] = Future {
       Thread.sleep(1);
       "Hello, Welcome to Geeks for Geeks !!!";
     };
     val result: Future[Unit] = futureString.map { str =>
       println(str);
     };
     futureString.flatMap { str =>
       println(str);
       Future.successful(());
     };
     Thread.sleep(20);
   };
};

Output
Hello, Welcome to Geeks for Geeks !!!
Hello, Welcome to Geeks for Geeks !!!


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads