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
解决方法
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?
本书基本上试图在函数的编译时和运行时表示之间进行区分,因此当他们说“函数文字”时,你会理解他们在谈论前者,当他们说“函数值”时,后者.