简体   繁体   English

使用val的Scala中的函数文字

[英]Function literal in Scala using val

In following code: 在以下代码中:

scala> val double = (i: Int) => {
|     println("I am here")
|     i * 2
|   }
double: Int => Int = $$Lambda$1090/773348080@6ae9b2f0

scala> double(4)
I am here
res22: Int = 8

scala> val evenFunc: (Int => Boolean) = {
|                   println("I am here");
|                    (x => x % 2 == 0)
|              }
I am here
evenFunc: Int => Boolean = $$Lambda$1091/373581540@a7c489a

scala> double
res23: Int => Int = $$Lambda$1090/773348080@6ae9b2f0

scala> evenFunc
res24: Int => Boolean = $$Lambda$1091/373581540@a7c489a

scala> evenFunc(10)
res25: Boolean = true

scala> def incr(x:Int) = x+1
incr: (x: Int)Int

scala> incr
<console>:13: error: missing argument list for method incr
Unapplied methods are only converted to functions when a function type is 
expected.
You can make this conversion explicit by writing `incr _` or `incr(_)` 
instead of `incr`.
incr

double and evenFunc are function variables and we have assigned function literals to them.But as output shows, when we call double, println statement is also executed.But evenFunc doesn't execute println statement, except when defined. double和evenFunc是函数变量,我们已经为它们分配了函数文字。但是如输出所示,当我们调用double时,还会执行println语句。但是evenFunc不会执行println语句,除非已定义。 incr is defined with keyword def, so its behaviour is as expected. incr是用关键字def定义的,因此其行为符合预期。

Why do double and evenFunc behave differently, even though both refer to function literals? 即使double和evenFunc都引用函数文字,为什么它们的行为也有所不同?

The point at which the input parameter is received is the pivot. 接收输入参数的点是枢轴。

If you change evenFunc from... 如果从...更改evenFunc ...

println("I am here")
x => x % 2 == 0

... to ... ... 至 ...

x =>
println("I am here")
x % 2 == 0

...you'll get the same behavior as observed with double . ...您将获得与double相同的行为。

What comes before the received argument is evaluated/executed where the function is defined. 在定义函数的位置评估/执行接收到的参数之前的内容。 What comes after the received argument is executed each time the function is invoked. 每次调用函数后,执行接收到的参数之后会发生什么。

The difference is rather clear 区别很明显

(i: Int) => {
     println("I am here")
     i * 2
 }

{
   println("I am here");
   (x => x % 2 == 0)
}

The function literal is defined as (param list) => body . 函数文字定义为(param list) => body Hence, the println statement in the 2nd is evaluated before and beyond the the function literal so that it's not part of the function body. 因此,第二条中的println语句在函数文字之前和之后进行求值,因此它不属于函数主体。

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

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