In scala it is possible to define a local block in a function. The local block evaluates to the last statements, for example,
val x = {val x =1;x+1}
Here x==2
, the inner val x
is local to that block.
However those local blocks can cause sneaky bugs when writing anonymous classes. For example (from scala's reference)
new Iterator[Int]
{...} // new anonymous class inheriting from Iterator[Int]
new Iterator[Int]
{...} //new Iterator[Int] followed by a "dangling" local block
Differntiating between the two cases is frustrating.
Sometimes those two code snippets can compile, for instance if instead of Iterator[Int]
, Range(0,1,1)
is used.
I thought about it and couldn't find a case where "dangling" local block (ie, a local block whose value isn't use) is needed (or makes the code more elegant).
Is there a case where we want a local block, without using its value (and without putting it in a different function and calling this function)? I'll be glad for an example.
If not, I think it would be nice to issue a warning (or even forbid altogther) whenever scalac
encounter "dangling" local block. Am I missing something?