http://stackoverflow.com/questions/2529184/difference-between-method-and-function-in-scala

A Function Type is (roughly) a type of the form (T1, ..., Tn) => U, which is a shorthand for the trait FunctionN in the standard library. Anonymous Functions and Method Values have function types, and function types can be used as part of value, variable and function declarations and definitions. In fact, it can be part of a method type.

A Method Type is a non-value type. That means there is no value - no object, no instance - with a method type. As mentioned above, a Method Value actually has a Function Type. A method type is a def declaration - everything about a def except its body.

Value Declarations and Definitions and Variable Declarations and Definitions are val and var declarations, including both type and value - which can be, respectively, Function Type andAnonymous Functions or Method Values. Note that, on the JVM, these (method values) are implemented with what Java calls "methods".

A Function Declaration is a def declaration, including type and body. The type part is the Method Type, and the body is an expression or a block. This is also implemented on the JVM with what Java calls "methods".

Finally, an Anonymous Function is an instance of a Function Type (ie, an instance of the trait FunctionN), and a Method Value is the same thing! The distinction is that a Method Value is created from methods, either by postfixing an underscore (m _ is a method value corresponding to the "function declaration" (defm), or by a process called eta-expansion, which is like an automatic cast from method to function.

That is what the specs say, so let me put this up-front: we do not use that terminology! It leads to too much confusion between so-called "function declaration", which is a part of the program (chapter 4 -- basic declarations) and "anonymous function", which is an expression, and "function type", which is, well a type -- a trait.

The terminology below, and used by experienced Scala programmers, makes one change from the terminology of the specification: instead of saying function declaration, we say method. Or even method declaration. Furthermore, we note that value declarations and variable declarations are also methods for practical purposes.

So, given the above change in terminology, here's a practical explanation of the distinction.

A function is an object that includes one of the FunctionX traits, such as Function0Function1Function2, etc. It might be including PartialFunction as well, which actually extends Function1.

Let's see the type signature for one of these traits:

trait Function2[-T1, -T2, +R] extends AnyRef

This trait has one abstract method (it has a few concrete methods as well):

def apply(v1: T1, v2: T2): R

And that tell us all that there is to know about it. A function has an apply method which receives Nparameters of types T1, T2, ..., TN, and returns something of type R. It is contra-variant on the parameters it receives, and co-variant on the result.

That variance means that a Function1[Seq[T], String] is a subtype of Function1[List[T], AnyRef]. Being a subtype means it can be used in place of it. One can easily see that if I'm going to call f(List(1, 2, 3)) and expect an AnyRef back, either of the two types above would work.

Now, what is the similarity of a method and a function? Well, if f is a function and m is a method local to the scope, then both can be called like this:

val o1 = f(List(1, 2, 3))
val o2 = m(List(1, 2, 3))

These calls are actually different, because the first one is just a syntactic sugar. Scala expands it to:

val o1 = f.apply(List(1, 2, 3))

Which, of course, is a method call on object f. Functions also have other syntactic sugars to its advantage: function literals (two of them, actually) and (T1, T2) => R type signatures. For example:

val f = (l: List[Int]) => l mkString ""
val g: (AnyVal) => String = {
case i: Int => "Int"
case d: Double => "Double"
case o => "Other"
}

Another similarity between a method and a function is that the former can be easily converted into the latter:

val f = m _

Scala will expand that, assuming m type is (List[Int])AnyRef into (Scala 2.7):

val f = new AnyRef with Function1[List[Int], AnyRef] {
def apply(x$1: List[Int]) = this.m(x$1)
}

On Scala 2.8, it actually uses an AbstractFunction1 class to reduce class sizes.

Notice that one can't convert the other way around -- from a function to a method.

Methods, however, have one big advantage (well, two -- they can be slightly faster): they can receive type parameters. For instance, while f above can necessarily specify the type of List it receives (List[Int] in the example), m can parameterize it:

def m[T](l: List[T]): String = l mkString ""

I think this pretty much covers everything, but I'll be happy to complement this with answers to any questions that may remain.

scala学习笔记:函数与方法的更多相关文章

  1. Scala学习笔记——函数和闭包

    1.本地函数 可以在一个方法内再次定义一个方法,这个方法就是外部方法的内部私有方法,省略了private关键字 2.头等函数 var increase = (x: Int) => x + 1 S ...

  2. golang学习笔记---函数、方法和接口

    函数:对应操作序列,是程序的基本组成元素. 函数有具名和匿名之分:具名函数一般对应于包级的函数,是匿名函数的一种特例,当匿名函数引用了外部作用域中的变量时就成了闭包函数,闭包函数是函数式编程语言的核心 ...

  3. golang学习笔记--函数和方法

    在go中,函数类型是一等类型,这意味着可以吧函数当做一个值来传递和使用. func divide(dividend int,divisor int)(int,error){ //省略部分代码 } 参数 ...

  4. 基于.net的分布式系统限流组件 C# DataGridView绑定List对象时,利用BindingList来实现增删查改 .net中ThreadPool与Task的认识总结 C# 排序技术研究与对比 基于.net的通用内存缓存模型组件 Scala学习笔记:重要语法特性

    基于.net的分布式系统限流组件   在互联网应用中,流量洪峰是常有的事情.在应对流量洪峰时,通用的处理模式一般有排队.限流,这样可以非常直接有效的保护系统,防止系统被打爆.另外,通过限流技术手段,可 ...

  5. Scala学习笔记及与Java不同之处总结-从Java开发者角度

    Scala与Java具有很多相似之处,但又有很多不同.这里主要从一个Java开发者的角度,总结在使用Scala的过程中所面临的一些思维转变. 这里仅仅是总结了部分两种语言在开发过程中的不同,以后会陆续 ...

  6. 深度学习笔记:优化方法总结(BGD,SGD,Momentum,AdaGrad,RMSProp,Adam)

    深度学习笔记:优化方法总结(BGD,SGD,Momentum,AdaGrad,RMSProp,Adam) 深度学习笔记(一):logistic分类 深度学习笔记(二):简单神经网络,后向传播算法及实现 ...

  7. 《python基础教程(第二版)》学习笔记 函数(第6章)

    <python基础教程(第二版)>学习笔记 函数(第6章) 创建函数:def function_name(params):  block  return values 记录函数:def f ...

  8. scala 学习笔记二 方法与函数

    1.介绍 Scala 有方法与函数,二者在语义上的区别很小.Scala 方法是类的一部分,而函数是一个对象可以赋值给一个变量.换句话来说在类中定义的函数即是方法. Scala 中的方法跟 Java 的 ...

  9. Scala学习笔记之:tuple、array、Map

    [TOC] 本文<快学Scala>的笔记 tuple学习笔记 tuple的定义 对偶是元组(tuple)的最简单形态--元组是不同类型的值的聚集. 元组的值是通过将单个值包含在圆括号中构成 ...

  10. 【大数据】Scala学习笔记

    第 1 章 scala的概述1 1.1 学习sdala的原因 1 1.2 Scala语言诞生小故事 1 1.3 Scala 和 Java  以及 jvm 的关系分析图 2 1.4 Scala语言的特点 ...

随机推荐

  1. openstack学习线路指导

    原文链接: http://www.aboutyun.com/thread-7225-1-1.html 网上很多hadoop资料,openstack资料相对较少,这里整理一下,帮助初学者尽快入门. 首先 ...

  2. Win7 NFS 设置详解 | X-Space

    Win7 NFS 设置详解 | X-Space Win7 NFS 设置详解

  3. INTERIGHT 京东自营旗舰店-京东 要把凡客给弄残啊这是。。

    INTERIGHT 京东自营旗舰店-京东

  4. light oj 1008 - Fibsieve`s Fantabulous Birthday

    1008 - Fibsieve`s Fantabulous Birthday   PDF (English) Statistics Forum Time Limit: 0.5 second(s) Me ...

  5. nyoj 289 苹果

    苹果 时间限制:3000 ms  |  内存限制:65535 KB 难度:3   描述 ctest有n个苹果,要将它放入容量为v的背包.给出第i个苹果的大小和价钱,求出能放入背包的苹果的总价钱最大值. ...

  6. [OC Foundation框架 - 22] 集合的内存管理

    A.集合的手动内存管理 NSArray addObject: 加入的元素执行一次retain removeObject: 被删除的元素执行一次release removeAllObjects: 所有元 ...

  7. [Objective-c 基础 - 3.3] @property属性详解

    ARC     自动引用计数 ARC不是垃圾回收,而是编译器自动插入代码来减少程序员的代码输入和失误.     同时比垃圾和效率要高,因为其不影响运行时间,相当于自己管理内存.     总是通过属性来 ...

  8. Qt 固定窗口【worldsing 笔记】

    w.setWindowFlags(Qt::WindowMinimizeButtonHint); //禁止最大化按钮 w.setFixedSize(1024,587);//固定窗口大小

  9. Java远程方法调用(RMI)

    Java RMI 指的是远程方法调用 (Remote Method Invocation).它是一种机制,能够让在某个 Java 虚拟机上的对象调用另一个 Java 虚拟机中的对象上的方法.可以用此方 ...

  10. 【C++深入浅出】设计模式学习之单例模式

    但凡成为大家公认的模式,都是有一些不可小觑的威力,今天分享一个简单的设计模式:单例模式. 单例模式用于一些只希望有一个实例的类或者只希望执行一次的操作:校长只能有一个.老板只能有一个.用户点击弹窗只希 ...