views:

146

answers:

2

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?

+4  A: 

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

eed3si9n
I'm with you!A good code style is very important.
Eastsun
I dislike this coding style (in Java I put opening braces on new lines) but semicolon inference forces me to use it in Scala. Down with semicolon inference!
starblue
+1  A: 
  {
    import my.crazy.implicit.functions._

    // use them...
  }

  // code I know isn't touched by them.
Mitch Blevins