这编译:
paragraphs.map { a =>
}.filter { b =>
}.map { c =>
}.sortBy { d =>
}.reverse
Run Code Online (Sandbox Code Playgroud)
这样做:
paragraphs map { a =>
} filter { b =>
} map { c =>
} sortBy { d =>
} reverse // <- warning about postfix notation
Run Code Online (Sandbox Code Playgroud)
但这不是(无法解析sortBy中的变量):
paragraphs map { a =>
} filter { b =>
} map { c =>
} sortBy { d =>
}.reverse
Run Code Online (Sandbox Code Playgroud)
是运营商优先吗?如果是这样的话,更喜欢一个版本的原因是什么?
点优先,所以它得到的是:
(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)
^
Run Code Online (Sandbox Code Playgroud)
并{b => true}没有方法reverse.从技术上讲,{b => true}它甚至不是一个有效的表达式,但您可以PartialFunction通过指定期望的类型使其成为有效b,从而为您提供更有用的错误消息:
(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
^
Run Code Online (Sandbox Code Playgroud)
但请注意,现在不推荐使用后缀运算符(即没有点),如果您尝试使用它们,则会收到警告:
~$ 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
53 次 |
| 最近记录: |