【发布时间】:2015-10-31 11:43:20
【问题描述】:
以下是两种以不同样式声明的方法。两者都在做同样的工作。我想知道为什么
- 检查函数类型需要不同的语法(黄色 块)
- 调用函数需要不同的语法(绿色块)
- scala repl 上两种方法的声明给出了不同的结果 (红块)
另外,请建议,哪种方式是首选的声明方式 方法或这两种风格是否有任何特殊用例 方法声明?
编辑 1:
以下是截图中的命令:-
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> def add(x:Int, y :Int): Int = {x+y}
add: (x: Int, y: Int)Int
scala> def sum = (x:Int, y:Int) => {x+y}
sum: (Int, Int) => Int
scala> :t add
<console>:12: error: missing arguments for method add;
follow this method with `_' if you want to treat it as a partially applied function
add
^
scala> :t add(_, _)
(Int, Int) => Int
scala> :t sum
(Int, Int) => Int
scala> add
<console>:12: error: missing arguments for method add;
follow this method with `_' if you want to treat it as a partially applied function
add
^
scala> add(_, _)
res1: (Int, Int) => Int = <function2>
scala> sum
res2: (Int, Int) => Int = <function2>
编辑 2:
@Shadowlands
我在dzone 上读到过,其中指出“当需要一个函数但提供了一个方法时,它将自动转换为一个函数。这称为 ETA 扩展。”。
现在,如果 ETA 小心地将您的方法转换为函数。是否真的需要使用 sum 样式,因为它看起来像 Function 对象的额外开销。
【问题讨论】:
-
请复制这里的文字而不是截图。
标签: function scala methods types call