下划线定义匿名函数的规则是什么? [英] What are the rules to govern underscore to define anonymous function?

查看:30
本文介绍了下划线定义匿名函数的规则是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 _ 作为占位符来创建匿名函数,问题是我无法预测 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))

第 2 个第 3 个正确转变为我想要的.

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:

  1. 如果下划线是方法的参数,则作用域将在该方法之外,否则分别遵循以下规则;
  2. 如果下划线在由 () 或 {} 分隔的表达式内,则将使用包含下划线的最里面的此类分隔符;
  3. 在所有其他条件相同的情况下,将使用可能的最大表达式.
  1. If the underscore is an argument to a method, then the scope will be outside that method, otherwise respective the rules below;
  2. If the underscore is inside an expression delimited by () or {}, the innermost such delimiter that contains the underscore will be used;
  3. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆