1

Why in the following code, the compiler doesn't give error even if the return type is Future[Future[Unit]] instead of Future[Unit]?

//compiles even though return is Future[Future[Unit]]. Not expected. def test1:Future[Unit] = Future{ Future{ println("something")} } //doesn't compile because return is Future[Future[Int]] . Expected def test:Future[Int] = Future{ Future{1} } 
3
  • 1
    This is due the compiler rewrites the code as: Future{ Future{ println("something") }; () } - As you can see, the Unit is being inserted at the end of the method. To prevent this, enable the -Ywarn-value-discard compiler flag. Commented Jul 19, 2019 at 16:45
  • Thanks But why is compiler doing this? Commented Jul 19, 2019 at 16:47
  • 1
    So you can write this def foo(): Unit = { a += 1 } or things like that, the idea is that if unit is expected, it will insert it for you, so you do not have to write it manually. For java-like code it is useful, but for more pure code that can cause troubles. That is why the compiler flag exists, you should always use it, together with all these. Commented Jul 19, 2019 at 17:01

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.