问题
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?
回答1:
{
import my.crazy.implicit.functions._
// use them...
}
// code I know isn't touched by them.
回答2:
Why not write
new Iterator[Int] {
...
}
Edit: This is the style used by Programming in Scala (see sample chapter pdf)
new RationalTrait {
val numerArg = 1 * x
val denomArg = 2 * x
}
and Java Coding Conventions.
Open brace "{" appears at the end of the same line as the declaration statement
来源:https://stackoverflow.com/questions/1525446/dangling-local-blocks-in-scala