为什么单个下划线字符是 lambda 参数的非法名称?
Why is a single underscore character an illegal name for a lambda parameter?
我尝试命名一个 lambda 参数 _
,例如(精简版):
Consumer<Object> c = _ -> {};
因为我想表示一个参数被忽略了,但是我得到了以下编译器错误:
use of '_' as an identifier is forbidden for lambda parameters
这对我来说是个惊喜。有意思的是,两个下划线就可以了:
Consumer<Object> c = __ -> {}; // no compile error
所以不是一般的下划线字符,而是单个下划线字符
为什么单下划线名称被特别禁止?
原因在this post from Brian Goetz自己表示:
We are "reclaiming" the syntactic real estate of "_" from the space of identifiers for use in future language features. However, because there are existing programs that might use it, it is a warning for identifiers that occur in existing syntactic positions for 8, and an error for lambda formals (since there is no existing code with lambdas.)
我尝试命名一个 lambda 参数 _
,例如(精简版):
Consumer<Object> c = _ -> {};
因为我想表示一个参数被忽略了,但是我得到了以下编译器错误:
use of '_' as an identifier is forbidden for lambda parameters
这对我来说是个惊喜。有意思的是,两个下划线就可以了:
Consumer<Object> c = __ -> {}; // no compile error
所以不是一般的下划线字符,而是单个下划线字符
为什么单下划线名称被特别禁止?
原因在this post from Brian Goetz自己表示:
We are "reclaiming" the syntactic real estate of "_" from the space of identifiers for use in future language features. However, because there are existing programs that might use it, it is a warning for identifiers that occur in existing syntactic positions for 8, and an error for lambda formals (since there is no existing code with lambdas.)