问题描述
我正在观看 Runar Bjarnason 为初学者介绍函数式编程,并在 14:45他定义了一个方法:
I am watching Runar Bjarnason present Functional Programming for Beginners, and at 14:45 he defines a method:
def isDivisibleBy(k: Int): Int => Boolean = i => i % k == 0
和一个函数:
val isEven = isDivisibleBy(2)
将 isEven
定义为函数而不是方法的利弊是什么?
What are the pros and cons of defining isEven
as a function rather than a method?
我已阅读 Scala 函数与方法 以及 Scala 中方法和函数的区别,我理解语义差异,但我想知道在这种情况下是否有更深层次的原因为什么函数可能比使用方法更可取:
I have read Scala Functions vs Methods as well as Difference between method and function in Scala, and I understand the semantic differences, but I wonder if there's some deeper reason in this case why a function might or might not be preferable to using a method:
def isEven = isDivisibleBy(2)
推荐答案
在幕后,函数和方法之间还有其他差异.通常,普通方法产生的开销比函数(从技术上讲是具有 apply
方法的对象)少.
Under the hood, there are other differences between functions and methods. Generally, a plain method generated less overhead than a function (which technically is an object with an apply
method).
但是,如果您尽量不去关心这些差异,而是将 def
、val
和 var
视为 fields 具有不同的语义,那么很简单 def
每次被调用时都会计算,而 val
只计算一次.
However, if you try not to care about those differences and think of def
, val
and var
as fields with different semantics, then it’s simply that def
evaluates every time it gets called while val
evaluates only once.
所以,val isEven = isDivisibleBy(2)
应该在定义时调用 isDivisibleBy(2)
并赋值 isDivisibleBy(2)
代码>.例如.它替换了
So, a val isEven = isDivisibleBy(2)
should call isDivisibleBy(2)
during its definition and assign the result of isDivisibleBy(2)
. E.g. it replaces the k
in
def isDivisibleBy(k: Int): Int => Boolean = i => i % k == 0
with 2
并分配最终表达式的结果(在这种情况下只有一个表达式):
with 2
and assigns the result of the final expression (in this case there is only one expression):
val isEven: Int => Boolean = i => i % 2 == 0
def isEven
另一方面,没有这样的评估,并且每次都会导致调用 isDivisibleBy(2).
def isEven
on the other hand does no such evaluation and results in a call to isDivisibleBy(2) every time.
这意味着,稍后,当您执行代码时,isEven(11)
会在 val
That means, later, when you execute the code, isEven(11)
generates in case of a val
11 % 2 == 0
如果是 def
,你将有
isDivisibleBy(2)(11)
并且只有在评估 isDivisibleBy
之后,您才会得到结果.
and only after evaluating isDivisibleBy
you’ll get the result.
你可以在isDivisibleBy
中添加一些调试代码来看看区别:
You can add some debug code to isDivisibleBy
to see the difference:
def isDivisibleBy(k: Int): Int => Boolean = {
println("evaluating isDivisibleBy")
i => i % k == 0
}
这篇关于Scala 中的函数与方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!