试图从 Scala 编程,第 2 版中找出本节的重要性。
A function literal is compiled into a class that when instantiated at run- time is a function value. Thus the distinction between function literals and values is that function literals exist in the source code, whereas function val- ues exist as objects at runtime. The distinction is much like that between classes (source code) and objects (runtime).
我真的不明白他们在这里想说什么。源代码中不存在函数值并且运行时不存在函数文字?
// literal
val addOne = (x: Int) => x + 1
// value
def add1(x: Int): Int = x + 1
我可以传递给另一个函数:
def doThing(thing: Int => Int) = thing(5)
doThing(addOne) // 6
doThing(add1) // 6
似乎函数文字也被放置在一个继承自
FunctionN
的类中。 (其中 N 是函数的元数)。他们试图在这里做出什么区别?
最佳答案
I don't really get what they're trying to say here.
您的函数文字和值示例不准确。这本书不是将方法与函数进行比较,而是在函数的两种不同“模式”之间进行区分。提示在第一句话中:
A function literal is compiled into a class that when instantiated at run-time is a function value.
在编译时键入:
val addOne = (x: Int) => x + 1
这就是本书所说的“函数文字”(或 Anonymous Function )。与通过键入获得字符串文字的方式相同:
val s = "Hello, World"
addOne
编译器是一个 Function1[Int, Int]
, 意思是 Int
并返回 Int
结果。函数文字语法( (x: Int) => x + 1
)是 FunctionN
上的语法糖,其中 N
由 arity 决定的功能。在运行时,编译器通过实例化一个类型为
Function1[Int, Int]
的对象来获取这个“函数文字”并“赋予它生命”。 ,从而创建一个可以调用、传递等的函数值。What distinction are they trying to make here?
这本书基本上试图区分函数的编译时和运行时表示,所以当他们说“函数文字”时,你会明白他们在谈论前者,而当他们说“函数值”时后者.
关于scala - 函数字面量 vs 函数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37086222/