管理下划线以定义匿名功能的规则是什么? [英] What are the rules to govern underscore to define anonymous function?
问题描述
我正在使用_
作为创建匿名函数的占位符,问题是我无法预测Scala将如何转换我的代码.更准确地说,它错误地确定了我想要的匿名功能有多大".
I am using _
as placeholder for creating anonymous function, and the problem is I cannot predict how Scala is going to transform my code. More precisely, it mistakenly determines how "large" the anonymous function I want.
List(1,2,3) foreach println(_:Int) //error !
List(1,2,3) foreach (println(_:Int)) //work
List(1,2,3) foreach(println(_:Int)) //work
使用-Xprint:typer
我可以看到Scala将第一个转换为大型匿名函数":
Using -Xprint:typer
I can see Scala transforms the first one into "a big anonymous function":
x$1 => List(1,2,3) foreach(println(x$1:Int))
工作2th 3th是正确转换为我想要的东西.
the worked 2th 3th are right transformation into what I want.
... foreach (x$1 => println(x$1:Int))
为什么呢?规则是什么?
Why this? What's the rule ?
推荐答案
确定下划线范围的简单规则:
Simple rules to determine the scope of underscore:
- 如果下划线是某个方法的参数,则范围将在该方法的之外,否则将使用以下规则;
- 如果下划线位于用()或{}分隔的表达式内,则将使用包含下划线的最里面的分隔符;
- 在所有其他条件相同的情况下,将使用可能的最大表达方式.
- If the underscore is an argument to a method, then the scope will be outside that method, otherwise respective the rules below;
- If the underscore is inside an expression delimited by () or {}, the innermost such delimiter that contains the underscore will be used;
- All other things being equal, the largest expression possible will be used.
因此,根据规则#1,合并范围将放置在(包括)println
之外,而不是println((x: Int) => x)
.
So, by the rule #1, instead of println((x: Int) => x)
, the scope will be placed outside (including) println
.
根据规则2,后两个示例将具有用圆括号分隔的函数,因此(x => println(x: Int))
.
By rule #2, the latter two examples will have the function delimited by parenthesis, so (x => println(x: Int))
.
根据规则3,第一个示例将是整个表达式,因为没有定界括号.
By rule #3, the first example will be the whole expression, as there are no delimiting parenthesis.
这篇关于管理下划线以定义匿名功能的规则是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!