[英]`Unit` Return Type of Closure
Given the following closure: 鉴于以下结束:
scala> def foo(x: Int) {
| def bar(y: Int) = x + y
| bar(55)
| }
foo: (x: Int)Unit
Why is its return type Unit
? 为什么它的返回类型Unit
? I would've expected an Int
. 我会期待一个Int
。
scala> foo(55)
scala>
You are using the procedure syntax. 您正在使用过程语法。 ie you don't have an =
after the method declaration, so the method will return Unit
. 即你在方法声明后没有=
,所以该方法将返回Unit
。 What you want is: 你想要的是:
scala> def foo(x: Int) = {
| def bar(y: Int) = x + y
| bar(55)
| }
foo: (x: Int)Int
The value of bar(55)
in your example is being discarded, which you can catch via compiler flag: 您的示例中的bar(55)
的值将被丢弃,您可以通过编译器标记捕获它:
$ scala -Ywarn-value-discard
scala> def foo(x: Int) {
| def bar(y: Int) = x + y
| bar(55)
| }
<console>:9: warning: discarded non-Unit value
bar(55)
^
foo: (x: Int)Unit
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.