Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why no dead code warning after return statement?

Tags:

return

scala

Can anyone explain why the method below is compiling without any error message? I expected a dead code warning or something like that. Is there a reason why it compiles?

def somethingAfterReturn(): Int = {
   println("That is ok..");
   return 1
   println("WTF is going on here?");
   3
}
like image 869
Marcin Sanecki Avatar asked Oct 21 '12 17:10

Marcin Sanecki


2 Answers

First, try this:

$ scala -e 'def somethingAfterReturn(): Int = { println("That is ok.."); return 1; println("WTF is going on here?"); 3 }'

no errors, right?

Then, try this:

$ scala -Ywarn-dead-code -e 'def somethingAfterReturn(): Int = { println("That is ok.."); return 1; println("WTF is going on here?"); 3 }'

By default, Scala ignore unreachable code.

like image 129
Alcides Queiroz Avatar answered Oct 11 '22 12:10

Alcides Queiroz


The compiler allows this because it is syntactically valid.

like image 20
Benjamin Tan Wei Hao Avatar answered Oct 11 '22 13:10

Benjamin Tan Wei Hao