“悬挂” scala中的本地块 [英] "dangling" local blocks in scala
问题描述
在scala中,可以在函数中定义一个局部块。本地块评估为最后一个语句,例如
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}
这里 x == 2
code> val x 是该块的本地。
Here x==2
, the inner val x
is local to that block.
但是,当编写匿名类时,这些本地块会导致鬼祟的错误。例如(来自scala的引用)
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
这两种情况之间的区分令人沮丧。
有时这两个代码片段可以编译,例如,而不是 Iterator [Int]
, Range(0,1,1)
被使用。
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.
我想到了,并且找不到一个dangling局部块(即,值为n (或使代码更优雅)。
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.
如果没有,我认为发布警告(甚至禁止别人)每当 scalac
遇到dangling本地块。我错过了什么?
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?
推荐答案
{
import my.crazy.implicit.functions._
// use them...
}
// code I know isn't touched by them.
这篇关于“悬挂” scala中的本地块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!