scala学习笔记:函数与方法
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" (def
) m
), 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 Function0
, Function1
, Function2
, 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学习笔记:函数与方法的更多相关文章
- Scala学习笔记——函数和闭包
1.本地函数 可以在一个方法内再次定义一个方法,这个方法就是外部方法的内部私有方法,省略了private关键字 2.头等函数 var increase = (x: Int) => x + 1 S ...
- golang学习笔记---函数、方法和接口
函数:对应操作序列,是程序的基本组成元素. 函数有具名和匿名之分:具名函数一般对应于包级的函数,是匿名函数的一种特例,当匿名函数引用了外部作用域中的变量时就成了闭包函数,闭包函数是函数式编程语言的核心 ...
- golang学习笔记--函数和方法
在go中,函数类型是一等类型,这意味着可以吧函数当做一个值来传递和使用. func divide(dividend int,divisor int)(int,error){ //省略部分代码 } 参数 ...
- 基于.net的分布式系统限流组件 C# DataGridView绑定List对象时,利用BindingList来实现增删查改 .net中ThreadPool与Task的认识总结 C# 排序技术研究与对比 基于.net的通用内存缓存模型组件 Scala学习笔记:重要语法特性
基于.net的分布式系统限流组件 在互联网应用中,流量洪峰是常有的事情.在应对流量洪峰时,通用的处理模式一般有排队.限流,这样可以非常直接有效的保护系统,防止系统被打爆.另外,通过限流技术手段,可 ...
- Scala学习笔记及与Java不同之处总结-从Java开发者角度
Scala与Java具有很多相似之处,但又有很多不同.这里主要从一个Java开发者的角度,总结在使用Scala的过程中所面临的一些思维转变. 这里仅仅是总结了部分两种语言在开发过程中的不同,以后会陆续 ...
- 深度学习笔记:优化方法总结(BGD,SGD,Momentum,AdaGrad,RMSProp,Adam)
深度学习笔记:优化方法总结(BGD,SGD,Momentum,AdaGrad,RMSProp,Adam) 深度学习笔记(一):logistic分类 深度学习笔记(二):简单神经网络,后向传播算法及实现 ...
- 《python基础教程(第二版)》学习笔记 函数(第6章)
<python基础教程(第二版)>学习笔记 函数(第6章) 创建函数:def function_name(params): block return values 记录函数:def f ...
- scala 学习笔记二 方法与函数
1.介绍 Scala 有方法与函数,二者在语义上的区别很小.Scala 方法是类的一部分,而函数是一个对象可以赋值给一个变量.换句话来说在类中定义的函数即是方法. Scala 中的方法跟 Java 的 ...
- Scala学习笔记之:tuple、array、Map
[TOC] 本文<快学Scala>的笔记 tuple学习笔记 tuple的定义 对偶是元组(tuple)的最简单形态--元组是不同类型的值的聚集. 元组的值是通过将单个值包含在圆括号中构成 ...
- 【大数据】Scala学习笔记
第 1 章 scala的概述1 1.1 学习sdala的原因 1 1.2 Scala语言诞生小故事 1 1.3 Scala 和 Java 以及 jvm 的关系分析图 2 1.4 Scala语言的特点 ...
随机推荐
- leetcode–Binary Tree Maximum Path Sum
1.题目说明 Given a binary tree, find the maximum path sum. The path may start and end at any node in t ...
- 那传说中的P、NP以及NPC问题
那传说中的P.NP以及NPC问题 (这里只是自己的一些总结) 在讲这几个问题之前,有几个东西是必须要说的,包括时间复杂度.空间复杂度.图灵机什么的.那么我们就慢慢来一一说来. 图灵机:图 ...
- HDU-4704 Sum 大数幂取模
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4704 题意:求a^n%m的结果,其中n为大数. S(1)+S(2)+...+S(N)等于2^(n-1) ...
- centos firefox中文乱码问题
下载两个rpm包 fonts-chinese-3.02-9.6.e15.noarch.rpm fonts-ISO8859-2-75dpi-1.0-17.1.noarch.rpm 然后安装rmp rpm ...
- HDU 3488--Tour(KM or 费用流)
因为每个点只能经过一次 所以考虑拆点 这题有坑,有重边.. KM算法 把一个点拆成入点和出点 入点在X部,出点在Y步. 如果u,v之间有路径,就在X部的u点连接Y部的v点 求完美匹配. 当完美匹配的时 ...
- Java HashMap 核心源码解读
本篇对HashMap实现的源码进行简单的分析. 所使用的HashMap源码的版本信息如下: /* * @(#)HashMap.java 1.73 07/03/13 * * Copyright 2006 ...
- Android实例-解决虚拟键盘遮挡问题(XE8+小米2)
结果: 1.可以自动向上移动,来防遮挡,但同时发现个问题,如果是按硬件返回没有问题,要是点输入法(QQ.百度输入法)上的隐藏就不行了. 2.点击Edit2后出现输入法,点输入法上的隐藏后, 再点Edi ...
- 【Stage3D学习笔记续】山寨Starling(八):核心优化(批处理)的实现
批处理是使GPU进行高效绘制的一种技术手段,也是整个渲染流程中最核心的技术,到目前为止我们并没有使用到这种技术手段,下面我们看看我们现在的渲染机制. 先想一想我们最开始是怎么向GPU绘制一幅图像的,可 ...
- 关于cshtml中的js对动态编译支持的问题
问题:MVC4中支持对ViewBag.ViewDate等的动态编译,但是在js中对它的支持就是有问题.虽然是可以动态编译,但是动态编译之后,断点无法获取. $.getJSON("/api/A ...
- Graph(2014辽宁ACM省赛)
问题 F: Graph 时间限制: 1 Sec 内存限制: 128 MB 提交: 30 解决: 5 [cid=1073&pid=5&langmask=0" style=& ...