4
def fun = { val a = Future {println("Inside Future"); throw new Exception("Discomfort in the sea has pulled itself upon me"); 5} a onComplete {_ => Thread.sleep(5000); println("Inside map") } a } 

Above is a very simple snippet. The return type is Future. Is there a better way without storing the value of Future in a val and still have onComplete but still be able to return the Future?

2 Answers 2

3

andThen is there to help with side effects. Note that the value that is returned inside the call to andThen is ignored, even if an exception is thrown.

def fun = { Future {println("Inside Future"); throw new Exception("Discomfort in the sea has pulled itself upon me"); 5} .andThen {case _ => Thread.sleep(5000); println("Inside map") } } 
Sign up to request clarification or add additional context in comments.

Comments

2

onComplete returns unit so if you specifically want to use onComplete you need the temporary variable. Alternatively, with Scala 2.12, you can use transform to do something similar. Note that you always need the return value:

 def fun = { Future { println("Inside Future") throw new Exception("Discomfort in the sea has pulled itself upon me") 5 }.transform { res => Thread.sleep(5000) println("Inside map") res } } 

An alternative for any Scala version is to just do both map and recover with the same body, but it wouldn't be as elegant.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.