“dangling” local blocks in scala

烂漫一生 提交于 2020-01-15 05:18:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!