scala 这三种在Scala中定义函数的方式的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3646756/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Differences between these three ways of defining a function in Scala
提问by qrest
Given three ways of expressing the same function f(a) := a + 1:
给出三种表达相同函数的方式f(a) := a + 1:
val f1 = (a:Int) => a + 1
def f2 = (a:Int) => a + 1
def f3:(Int => Int) = a => a + 1
How do these definitions differ? The REPL does not indicate any obvious differences:
这些定义有何不同?REPL 没有表明任何明显的差异:
scala> f1
res38: (Int) => Int = <function1>
scala> f2
res39: (Int) => Int = <function1>
scala> f3
res40: (Int) => Int = <function1>
回答by Hyman
Inside a class, valis evaluated on initialization while defis evaluated only when, and every time, the function is called. In the code below you will see that x is evaluated the first time the object is used, but not again when the x member is accessed. In contrast, y is not evaluated when the object is instantiated, but is evaluated every time the member is accessed.
在类内部,val在初始化时评估,而def仅在每次调用函数时评估。在下面的代码中,您将看到 x 在第一次使用对象时被评估,但在访问 x 成员时不会再次评估。相比之下, y 在对象被实例化时不被评估,而是在每次访问成员时被评估。
class A(a: Int) {
val x = { println("x is set to something"); a }
def y = { println("y is set to something"); a }
}
// Prints: x is set to something
val a = new A(1)
// Prints: "1"
println(a.x)
// Prints: "1"
println(a.x)
// Prints: "y is set to something" and "1"
println(a.y)
// Prints: "y is set to something" and "1"
println(a.y)
回答by missingfaktor
f1is a function that takes an integer and returns an integer.
f1是一个函数,它接受一个整数并返回一个整数。
f2is a method with zero arity that returns a function that takes an integer and returns an integer. (When you type f2at REPL later, it becomes a call to the method f2.)
f2是一个具有零元数的方法,它返回一个函数,该函数接受一个整数并返回一个整数。(当您f2稍后在 REPL 中键入时,它变成了对方法的调用f2。)
f3is same as f2. You're just not employing type inference there.
f3与 相同f2。你只是没有在那里使用类型推断。
回答by Alexander
Executing a definition such as defx = ewill not evaluate the expression e. Instead eis evaluated whenever xis used. Alternatively, Scala offers a value definition valx = e, which does evaluate the right-hand-side eas part of the evaluation of the definition. If xis then used subsequently, it is immediately replaced by the pre-computed value of e, so that the expression need not be evaluated again.
执行诸如defx = e的定义不会计算表达式e。相反,每当使用x时都会评估e。或者,Scala 提供了一个值定义 valx = e,它确实将右侧的e 计算为定义计算的一部分。如果随后使用x,则立即将其替换为e的预先计算值,因此无需再次计算表达式。
Scala By Example by Martin Odersky
Scala By Example by Martin Odersky

