繁体   English   中英

为什么Scala无法编译包含空格和点的混合功能链?

[英]Why Scala can't compile function chains with a mix of spaces and dots?

这样编译:

paragraphs.map { a =>

}.filter { b =>

}.map { c =>

}.sortBy { d =>

}.reverse

这样:

paragraphs map { a =>

} filter { b =>

} map { c =>

} sortBy { d =>

} reverse // <- warning about postfix notation

但这不能(无法解析sortBy中的变量):

paragraphs map { a =>

} filter { b =>

} map { c =>

} sortBy { d =>

}.reverse

是运算符优先级吗? 如果是这样,为什么一个版本优于另一个版本的原因是什么?

点优先,所以它得到的是:

(1 to 5) map { a => a } filter ({ b => true }.reverse)
<console>:11: error: missing parameter type
           (1 to 5) map { a => a } filter ({ b => true }.reverse)
                                             ^

而且{b => true}没有reverse方法。 从技术上讲, {b => true}甚至不是有效的表达式,但是您可以通过指定b的预期类型使其成为有效的PartialFunction ,从而为您提供更有用的错误消息:

(1 to 5) map { a => a } filter { b: Int => true }.reverse
<console>:11: error: value reverse is not a member of Int => Boolean
           (1 to 5) map { a => a } filter { b: Int => true }.reverse
                                                             ^

但是请注意,现在不建议使用后缀运算符(即,不带点),如果尝试使用后缀运算符,则会收到警告:

~$ scala -feature
Welcome to Scala version 2.11.7 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_79).
Type in expressions to have them evaluated.
Type :help for more information.

scala> (1 to 5) map { a => a } filter { b => true } reverse
<console>:11: warning: postfix operator reverse should be enabled
by making the implicit value scala.language.postfixOps visible.
This can be achieved by adding the import clause 'import scala.language.postfixOps'
or by setting the compiler option -language:postfixOps.
See the Scala docs for value scala.language.postfixOps for a discussion
why the feature should be explicitly enabled.
       (1 to 5) map { a => a } filter { b => true } reverse

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM