如何读取 Scala 函数参数链 [英] How to read a chain of Scala function parameters
问题描述
我正在尝试读取以下 2 个函数的参数列表:
I am trying to read the parameter-list of the following 2 functions:
1. def foo(action: => String => String) = "bar"
2. def foo(action: => () => String => String) = "bar"
- 名为foo"的函数接收名为action"的函数,该函数接收/返回???
- 一个名为foo"的函数接收一个名为action"的函数,该函数返回一个返回 ???
推荐答案
action
是一个按名称传递的函数,它接受一个String
并返回一个String
.action
是一个按名称传递的函数,它不需要返回一个函数,该函数接受一个String
并返回一个String
立>
action
is a passed-by-name function that takes aString
and returns aString
.action
is a passed-by-name function that takes nothing to return a function that takes aString
and returns aString
现在您可能会问,好吧,按名称传递参数是什么意思?"好吧……那是完全不同的蠕虫罐头.基本上,按名称传递的参数仅在函数中使用时进行评估,并且每次在函数中使用时都会进行评估.这允许的是类似短路的东西,如下
Now you might ask, "Well, what does it mean for a parameter to be passed-by-name?" Alright... that's a whole different can of worms. Basically, a passed by name parameter is only evaluated when it's used in the function, and every time that it's used in the function. What this allows for is something like short-circuiting, as follows
def orOperator(left: Boolean, right: => Boolean) : Boolean = if (left) true else right
在这种情况下,如果发现 left
为真,运算符将短路(并在不计算/评估 right
的情况下终止).
In this case, the operator will short-circuit (and terminate without computing/evaluating right
) if it finds left
to be true.
所以......你对这些参数的看法是相似的.它们是不求值的函数——出于某种原因——除非/直到它们在函数体中被命名.我不明白这样做的动机,但是......事情就是这样.我希望这会有所帮助.
So... what you have with these parameters is something similar. They are functions that do not evaluate—for some reason—unless/until they are named in the function body. I don't understand the motivation for that, but... that's how it is. I hope that helps.
这篇关于如何读取 Scala 函数参数链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!