scala - 函数字面量 vs 函数值

标签 scala function

试图从 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 上的语法糖,其中 Narity 决定的功能。

在运行时,编译器通过实例化一个类型为 Function1[Int, Int] 的对象来获取这个“函数文字”并“赋予它生命”。 ,从而创建一个可以调用、传递等的函数值。

What distinction are they trying to make here?



这本书基本上试图区分函数的编译时和运行时表示,所以当他们说“函数文字”时,你会明白他们在谈论前者,而当他们说“函数值”时后者.

关于scala - 函数字面量 vs 函数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37086222/

相关文章:

javascript - 如何构造 javascript 回调以便正确维护函数范围

c++ - C++ 中优雅的函数定义

c - 如何使用 struct 显示从 C 中另一个函数输入的数据

javascript - 在 JavaScript 中将数值转换为用字符填充的字符串

scala - 按边距分组

scala - 如何 groupBy 迭代器而不将其转换为 Scala 中的列表?

java - Scala 案例类到 Spring POJO

scala - 是否有 scalaTest 方法或属性可用于在所有套件中的所有测试之后仅运行一次

scala - 在没有 sbt 的情况下运行 Spark sbt 项目?

c - 如何将函数链接到 C 中的菜单